235 changes: 219 additions & 16 deletions pyKst/pykst.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#from PyQt4 import QtCore, QtNetwork
from PySide import QtCore, QtNetwork
from numpy import *
import tempfile

#from pykstpp import *

def b2str(val):
Expand Down Expand Up @@ -116,6 +118,14 @@ def set_tab(self,tab):
"""
self.send("setTab("+b2str(tab)+")")

def get_scalar_list(self):
""" returns the scalar names from kst """

x = str(self.send("getScalarList()"))

ret=x.split('|')
return ret

def new_generated_string(self, string, name=""):
""" Create a new generated string in kst.
Expand Down Expand Up @@ -216,6 +226,20 @@ def generated_vector(self, name):
"""
return GeneratedVector(self, 0, 0, 0, name, new=False)

def new_editable_vector(self, np_array = None, name=""):
""" Create a New Editable Vector in kst.
See :class:`EditableVector`
"""
return EditableVector(self, np_array, name)

def editable_vector(self, name):
""" Returns an Editable Vector from kst given its name.
See :class:`EditableVector`
"""
return Editable(self, None, name, new=False)

def new_data_matrix(self, filename, field, startX=0, startY=0, nX=-1, nY=-1,
minX=0, minY=0, dX=1, dY=1,name="") :
""" Create a New DataMatrix in kst.
Expand Down Expand Up @@ -275,6 +299,23 @@ def equation(self, name):
"""
return Equation(self, "", "", name, new=False)

def new_histogram(self, vector, bin_min=0, bin_max=1, n_bins=60,
normalization = 0, auto_bin = True, name=""):
""" Create a new histogram in kst.
See :class:`Histogram`
"""
return Histogram(self, vector, bin_min, bin_max, n_bins,
normalization, auto_bin, name)


def histogram(self, name):
""" Returns a histogram from kst given its name.
See :class:`Histogram`
"""
return Histogram(self, "", 0,0,0, name=name, new=False)

def new_spectrum(self,
vector,
sample_rate = 1.0,
Expand Down Expand Up @@ -335,7 +376,7 @@ def new_polynomial_fit(self, order, xVector, yVector, weightvector = 0, name = "
See :class:`PolynomialFit`
"""
return PolynomailFit(self, order, xVector, yVector, weightvector, name)
return PolynomialFit(self, order, xVector, yVector, weightvector, name)

def polynomial_fit(self, name):
""" Returns a polynomial fit from kst given its name.
Expand Down Expand Up @@ -766,6 +807,15 @@ def max(self):
def description_tip(self):
""" Returns a string describing the vector """
return self.client.send_si(self.handle, "descriptionTip()")

def get_numpy_array(self) :
""" get a numpy array which contains the kst vector values """
with tempfile.NamedTemporaryFile() as f:
self.client.send_si(self.handle, "store(" + f.name + ")")
array = fromfile(f.name, dtype = float64)

return array


class DataVector(VectorBase):
""" A vector in kst, read from a data source.
Expand Down Expand Up @@ -890,6 +940,40 @@ def change(self,X0, X1, N):
self.client.send_si(self.handle, "change("+b2str(X0)+","+b2str(X1)+
","+b2str(N)+")")

class EditableVector(VectorBase):
""" A vector in kst, which is editable from python.
This vector in kst can be created from a numpy array,
(with ''load()'') or edited point by point (with ''setValue()'').
"Create>Vector>Generate" from the menubar inside kst.
:param np_array: initialize the vector in kst to this (optional) 1D numpy array.
To create a from the num py array np::
import pykst as kst
client = kst.Client()
v = client.new_editable_vector(np)
"""
def __init__(self, client, np_array = None, name="", new=True) :
VectorBase.__init__(self,client)

if (new == True):
self.client.send("newEditableVector()")
if (np_array != None) :
assert(np_array.dtype == float64)

with tempfile.NamedTemporaryFile() as f:
np_array.tofile(f.name)
self.client.send("load(" + f.name + ")")

self.handle=self.client.send("endEdit()")
self.handle.remove(0,self.handle.indexOf("ing ")+4)

self.set_name(name)
else:
self.handle = name


class Matrix(NamedObject):
""" Convenience class. You should not use it directly."""
Expand Down Expand Up @@ -1178,12 +1262,15 @@ def set_point_density(self,density):
def set_point_type(self,pointType):
""" Sets the point type.
0 is an X, 1 is an open square, 2 is an open circle,
3 is a filled circle, 4 is a downward open triangle,
5 is an upward open triangle, 6 is a filled square,
7 is a plus, 8 is a asterix,
9 is a downward filled triangle, 10 is an upward filled triangle,
11 is an open diamond, and 12 is a filled diamond.
The available point types are::
0: X 1: open square
2: open circle, 3: filled circle
4: downward open triangle 5: upward open triangle
6: filled square 7: +
8: * 9: downward filled triangle
10: upward filled triangle 11: open diamond
12: filled diamond
"""
self.client.send_si(self.handle, "setPointType("+b2str(pointType)+")")
Expand Down Expand Up @@ -1342,13 +1429,15 @@ def setMatrix(self, matrix):
def setPalette(self, palette):
""" set the palette, selected by index.
0 Grey
1 Red
2 Spectrum
3 EOS-A
4 EOS-B
5 8 colors
6 Cyclical Spectrum
The available palettes are::
0: Grey
1: Red
2: Spectrum
3: EOS-A
4: EOS-B
5: 8 colors
6: Cyclical Spectrum
Note: this is not the same order as the dialog.
"""
Expand Down Expand Up @@ -1415,6 +1504,105 @@ def X(self) :
def set_x(self, xvector):
self.client.send_si(self.handle, "setInputVector(X,"+xvector.handle+")")

# Histogram ############################################################
class Histogram(NamedObject) :
""" A Histogram inside kst.
:param vector: the vector to take the histogram of
:param bin_min: the low end of the lowest bin
:param bin_max: the high end of the highest bin
:param n_bins: the number of bins
:param normalization: see below
:param auto_bin: if True, set xmin and xmax based on the vector
The normalization types are::
0: Number in the bin 1: Percent in the bin
2: Fraction in the bin 3: Peak is normalized to 1.0
"""
def __init__(self, client, vector, bin_min, bin_max, n_bins,
normalization = 0, auto_bin = False,
name="", new=True) :
NamedObject.__init__(self,client)

if (new == True):
self.client.send("newHistogram()")

self.client.send("change(" + vector.handle + "," +
b2str(bin_min) + "," +
b2str(bin_max) + "," +
b2str(n_bins) + "," +
b2str(normalization) + "," +
b2str(auto_bin) + ")")

self.handle=self.client.send("endEdit()")
self.handle.remove(0,self.handle.indexOf("ing ")+4)
self.set_name(name)
else:
self.handle = name

def Y(self) :
""" a vector containing the histogram values """
vec = VectorBase(self.client)
vec.handle = self.client.send_si(self.handle, "outputVector(H)")
return vec

def X(self) :
""" a vector containing the bin centers """
vec = VectorBase(self.client)
vec.handle = self.client.send_si(self.handle, "outputVector(B)")
return vec

def change(self, vector, bin_min, bin_max, n_bins,
normalization = 0, auto_bin = False):
""" Change Histogram parameters.
:param vector: the vector to take the histogram of
:param bin_min: the low end of the lowest bin
:param bin_max: the high end of the highest bin
:param n_bins: the number of bins
:param normalization: See :class:`Histogram`
:param auto_bin: if True, set xmin and xmax based on the vector
"""
self.client.send_si(self.handle, "change(" +
vector.handle + "," +
b2str(bin_min) + "," +
b2str(bin_max) + "," +
b2str(n_bins) + "," +
b2str(normalization) + "," +
b2str(auto_bin) + ")")

def bin_min(self):
""" the low end of the lowest bin """
retval = self.client.send_si(self.handle, "xMin()")
return retval

def bin_max(self):
""" the high end of the lowest bin """
retval = self.client.send_si(self.handle, "xMax()")
return retval

def n_bins(self):
""" the number of bins """
retval = self.client.send_si(self.handle, "nBins()")
return retval

def normalization(self):
""" how the bins are normalized
See :class:`Histogram`
"""
retval = self.client.send_si(self.handle, "normalizationType()")
return retval

def auto_bin(self):
""" if True, xmin and xmax are set based on the vector """
retval = self.client.send_si(self.handle, "autoBin()")
return retval

# Spectrum ############################################################
class Spectrum(NamedObject) :
""" An spectrum inside kst.
Expand All @@ -1431,6 +1619,20 @@ class Spectrum(NamedObject) :
:param sigma: only used if gausian apodization is selected.
:param output_type: index for the output type - see output_type()
:param interpolate_over_holes: interpolate over NaNs, if true.
The apodize funcition is::
0: default 1: Bartlett
2: Window 3: Connes
4: Cosine 5: Gaussian
6: Hamming 7: Hann
8: Welch 9: Uniform
The output type is::
0: Amplitude Spectral Density 1: Power Spectral Density
2: AmplitudeSpectrum 3: Power Spectrum
"""
def __init__(self, client,
Expand Down Expand Up @@ -1548,7 +1750,7 @@ def output_type(self):
The output type is::
0: Amplitude Spectral Density 1: Power Spectral Density = 1,
0: Amplitude Spectral Density 1: Power Spectral Density
2: AmplitudeSpectrum 3: Power Spectrum
"""
Expand Down Expand Up @@ -1636,7 +1838,7 @@ def intercept(self) :
return vec.value(0)

# POLYNOMIAL FIT ############################################################
class PolynomailFit(Fit) :
class PolynomialFit(Fit) :
""" A Polynomial fit inside kst.
:param order: The order of the fit
Expand Down Expand Up @@ -1923,6 +2125,7 @@ def set_text(self,text):
Scalars and scalar equations can be displayed live in labels.
When the scalar is updated, the label is updated.
The format is::
Scalar: [scalarname] eg [GYRO1:Mean(X4)]
Vector Element: [vectorName[index]] eg [GYRO1 (V2)[4]]
Equation: [=equation] eg [=[GYRO1:Mean(X4)]/[GYRO1:Sigma (X4)]]
Expand Down
2 changes: 1 addition & 1 deletion src/libkst/datavector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ bool DataVector::isValid() const {


ScriptInterface* DataVector::createScriptInterface() {
return new VectorDataSI(this);
return new DataVectorSI(this);
}


Expand Down
24 changes: 24 additions & 0 deletions src/libkst/editablevector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@

#include "editablevector.h"

#include "vectorscriptinterface.h"

// use KCodecs::base64Encode() in kmdcodecs.h
// Create QDataStream into a QByteArray
// qCompress the bytearray
#include <QXmlStreamWriter>
#include <QFile>

#include "debug.h"
namespace Kst {
Expand All @@ -38,6 +41,10 @@ const QString& EditableVector::typeString() const {
}


ScriptInterface* EditableVector::createScriptInterface() {
return new EditableVectorSI(this);
}

void EditableVector::setSaveData(bool save) {
Q_UNUSED(save)
}
Expand Down Expand Up @@ -78,6 +85,23 @@ void EditableVector::save(QXmlStreamWriter &s) {
s.writeEndElement();
}

/** used for scripting IPC.
accepts an open readable file.
fails silently */
void EditableVector::loadFromTmpFile(QFile &fp) {
qint64 n_read;

resize(fp.size()/sizeof(double));

n_read = fp.read((char *)_v, fp.size());

if (n_read != fp.size()) {
resize(n_read/sizeof(double));
}
internalUpdate(); // not sure if we need this here.
}


QString EditableVector::_automaticDescriptiveName() const {
QString name("(");
if (length()>=1) {
Expand Down
6 changes: 6 additions & 0 deletions src/libkst/editablevector.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
#include "vector.h"
#include "kst_export.h"

#include <QFile>

/**A vector with n editable pts
*@author cbn
*/
Expand All @@ -42,6 +44,10 @@ class KSTCORE_EXPORT EditableVector : public Vector {

virtual QString descriptionTip() const;

void loadFromTmpFile(QFile &fp);

ScriptInterface* createScriptInterface();

protected:
long double _sum;
EditableVector(ObjectStore *store);
Expand Down
2 changes: 1 addition & 1 deletion src/libkst/generatedvector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const QString& GeneratedVector::typeString() const {


ScriptInterface* GeneratedVector::createScriptInterface() {
return new VectorGenSI(this);
return new GeneratedVectorSI(this);
}


Expand Down
17 changes: 17 additions & 0 deletions src/libkst/vector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,23 @@ bool Vector::resize(int sz, bool init) {
}


/* used for scripting IPC
accepts an open writable file.
returns false on failure */
bool Vector::saveToTmpFile(QFile &fp) {
qint64 n_written;
qint64 n_write;

n_write = length()*sizeof(double);

n_written = fp.write((char *)_v, n_write);

fp.flush();

return (n_write == n_written);
}


void Vector::internalUpdate() {
int i, i0;
double sum, sum2, last, first, v;
Expand Down
4 changes: 4 additions & 0 deletions src/libkst/vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <math.h>

#include <QPointer>
#include <QFile>

#include "primitive.h"
#include "scalar.h"
Expand Down Expand Up @@ -113,6 +114,9 @@ class KSTCORE_EXPORT Vector : public Primitive

virtual bool resize(int sz, bool init = true);

/** dump the vector values to a raw binary file */
bool saveToTmpFile(QFile &fp);

virtual void setNewAndShift(int inNew, int inShift);

/** Clear out the vector by setting everything to 0.0 */
Expand Down
422 changes: 328 additions & 94 deletions src/libkst/vectorscriptinterface.cpp

Large diffs are not rendered by default.

97 changes: 88 additions & 9 deletions src/libkst/vectorscriptinterface.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,47 +18,126 @@
#include "scriptinterface.h"
#include "datavector.h"
#include "generatedvector.h"
#include "editablevector.h"

namespace Kst {

class KSTCORE_EXPORT VectorDataSI : public ScriptInterface
/*******************/
class KSTCORE_EXPORT VectorCommonSI : public ScriptInterface
{
Q_OBJECT

public:
QString value(QString& command);
QString length(QString&);
QString min(QString&);
QString max(QString&);
QString mean(QString&);
QString descriptionTip(QString&);
QString store(QString &command);

protected:
VectorPtr _vector;
QString noSuchFn(QString&) {return ""; }

};


/*******************/
class VectorSI;
typedef QString (VectorSI::*VectorInterfaceMemberFn)(QString& command);

class KSTCORE_EXPORT VectorSI : public VectorCommonSI
{
Q_OBJECT
DataVectorPtr vector;
public:
explicit VectorDataSI(DataVectorPtr it);
explicit VectorSI(VectorPtr it);
QString doCommand(QString);
bool isValid();
QByteArray endEditUpdate();

static ScriptInterface* newVector(ObjectStore *);

private:
QMap<QString,VectorInterfaceMemberFn> _fnMap;
};


/*******************/
class DataVectorSI;
typedef QString (DataVectorSI::*DataVectorInterfaceMemberFn)(QString& command);

class KSTCORE_EXPORT DataVectorSI : public VectorCommonSI
{
Q_OBJECT
public:
explicit DataVectorSI(DataVectorPtr it);
QString doCommand(QString);
bool isValid();
QByteArray endEditUpdate();

static ScriptInterface* newVector(ObjectStore *store);

QString change(QString &command);
QString field(QString &command);
QString filename(QString &command);
QString start(QString &command);
QString NFrames(QString &command);
QString skip(QString &command);
QString boxcarFirst(QString &command);

private:
DataVectorPtr _datavector;
QMap<QString,DataVectorInterfaceMemberFn> _fnMap;
};

class KSTCORE_EXPORT VectorGenSI : public ScriptInterface
/*******************/
class GeneratedVectorSI;
typedef QString (GeneratedVectorSI::*GeneratedVectorInterfaceMemberFn)(QString& command);

class KSTCORE_EXPORT GeneratedVectorSI : public VectorCommonSI
{
Q_OBJECT
GeneratedVectorPtr vector;
public:
explicit VectorGenSI(GeneratedVectorPtr it);
explicit GeneratedVectorSI(GeneratedVectorPtr it);
QString doCommand(QString);
bool isValid();
QByteArray endEditUpdate();

static ScriptInterface* newVector(ObjectStore *store);

QString change(QString &command);

private:
GeneratedVectorPtr _generatedvector;
QMap<QString,GeneratedVectorInterfaceMemberFn> _fnMap;
};


class KSTCORE_EXPORT VectorSI : public ScriptInterface
/*******************/
class EditableVectorSI;
typedef QString (EditableVectorSI::*EditableVectorInterfaceMemberFn)(QString& command);

class KSTCORE_EXPORT EditableVectorSI : public VectorCommonSI
{
Q_OBJECT
VectorPtr vector;
public:
explicit VectorSI(VectorPtr it);
explicit EditableVectorSI(EditableVectorPtr it);
QString doCommand(QString);
bool isValid();
QByteArray endEditUpdate();

static ScriptInterface* newVector(ObjectStore *);

QString load(QString &command);
QString setValue(QString &command);
QString resize(QString &command);
QString zero(QString &);

private:
EditableVectorPtr _editablevector;
QMap<QString,EditableVectorInterfaceMemberFn> _fnMap;

};

}
Expand Down
50 changes: 33 additions & 17 deletions src/libkstapp/scriptserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ ScriptServer::ScriptServer(ObjectStore *obj) : _server(new QLocalServer(this)),
_fnMap.insert("newGeneratedVector()",&ScriptServer::newGeneratedVector);

_fnMap.insert("getEditableVectorList()",&ScriptServer::getEditableVectorList);
_fnMap.insert("newEditableVectorAndGetHandle()",&ScriptServer::newEditableVectorAndGetHandle);
_fnMap.insert("newEditableVector()",&ScriptServer::newEditableVector);

_fnMap.insert("getMatrixList()",&ScriptServer::getMatrixList);
_fnMap.insert("newDataMatrix()",&ScriptServer::newDataMatrix);
Expand All @@ -122,7 +122,7 @@ ScriptServer::ScriptServer(ObjectStore *obj) : _server(new QLocalServer(this)),
_fnMap.insert("newEquation()",&ScriptServer::newEquation);

_fnMap.insert("getHistogramList()",&ScriptServer::getHistogramList);
// _fnMap.insert("newHistogram()",&ScriptServer::newHistogram);
_fnMap.insert("newHistogram()",&ScriptServer::newHistogram);

_fnMap.insert("getSpectrumList()",&ScriptServer::getSpectrumList);
_fnMap.insert("newSpectrum()",&ScriptServer::newSpectrum);
Expand Down Expand Up @@ -239,10 +239,15 @@ template<class T> QByteArray outputObjectList(
ObjectList<T> vl=_store->getObjects<T>();
QByteArray a;
typename ObjectList<T>::ConstIterator it = vl.constBegin();
bool first = true;
for(; it != vl.constEnd(); ++it) {
SharedPtr<T> v = (*it);
v->readLock();
a+='['%v->Name()%']';
if (!first) {
a += '|';
}
first = false;
a+=v->Name();
v->unlock();
}
if(a.size()) {
Expand Down Expand Up @@ -439,7 +444,16 @@ QByteArray ScriptServer::getEditableVectorList(QByteArray&, QLocalSocket* s,Obje
return outputObjectList<EditableVector>(s,_store);
}

QByteArray ScriptServer::newEditableVector(QByteArray&, QLocalSocket* s,ObjectStore*) {
if(_interface) {
return handleResponse("To access this function, first call endEdit()",s);
} else {
_interface = EditableVectorSI::newVector(_store); return handleResponse("Ok",s);
}
}


/*
QByteArray ScriptServer::newEditableVectorAndGetHandle(QByteArray&, QLocalSocket* s,ObjectStore*) {
EditableVectorPtr objectPtr=_store->createObject<EditableVector>();
Expand All @@ -450,13 +464,13 @@ QByteArray ScriptServer::newEditableVectorAndGetHandle(QByteArray&, QLocalSocket
UpdateServer::self()->requestUpdateSignal();
return handleResponse("Finished editing "+objectPtr->Name().toLatin1(),s);
}

*/

QByteArray ScriptServer::newDataVector(QByteArray&, QLocalSocket* s,ObjectStore*) {
if(_interface) {
return handleResponse("To access this function, first call endEdit()",s);
} else {
_interface = VectorDataSI::newVector(_store); return handleResponse("Ok",s);
_interface = DataVectorSI::newVector(_store); return handleResponse("Ok",s);
}
}

Expand All @@ -465,7 +479,7 @@ QByteArray ScriptServer::newGeneratedVector(QByteArray&, QLocalSocket* s,ObjectS
if(_interface) {
return handleResponse("To access this function, first call endEdit()",s);
} else {
_interface = VectorGenSI::newVector(_store); return handleResponse("Ok",s);
_interface = GeneratedVectorSI::newVector(_store); return handleResponse("Ok",s);
}
}

Expand Down Expand Up @@ -599,16 +613,14 @@ QByteArray ScriptServer::getHistogramList(QByteArray&, QLocalSocket* s,ObjectSto
return outputObjectList<Histogram>(s,_store);
}

/*
QByteArray ScriptServer::newHistogram(QByteArray&, QLocalSocket* s,ObjectStore*,const int&ifMode,

if(_interface) { return handleResponse("To access this function, first call endEdit()",s); }
else {
_interface = DialogLauncherSI::self->showHistogramDialog();
return handleResponse("Ok",s);
}
QByteArray ScriptServer::newHistogram(QByteArray&, QLocalSocket* s,ObjectStore*) {
if (_interface) {
return handleResponse("To access this function, first call endEdit()",s);
} else {
_interface = HistogramSI::newHistogram(_store); return handleResponse("Ok",s);
}
}
*/


QByteArray ScriptServer::getSpectrumList(QByteArray&, QLocalSocket* s,ObjectStore*_store) {
Expand Down Expand Up @@ -888,21 +900,21 @@ QByteArray ScriptServer::eliminate(QByteArray&command, QLocalSocket* s,ObjectSto
for(int i=0;i<vi.size();i++) {
if(command.contains(vi[i]->shortName().toLatin1())) {
vi[i]->hide(); // goodbye, memory.
return handleResponse("It died a peaceful death.",s);
return handleResponse("Done",s);
}
}
vi=ViewItem::getItems<ViewItem>();
}

return handleResponse("No such object (or it's hiding somewhere in the dark corners of Kst)",s);
return handleResponse("No such object",s);
} else {
if (RelationPtr relation = kst_cast<Relation>(o)) {
Data::self()->removeCurveFromPlots(relation);
}
_store->removeObject(o);
UpdateServer::self()->requestUpdateSignal();

return handleResponse("It died a peaceful death.",s);
return handleResponse("Done",s);
}
}

Expand Down Expand Up @@ -1019,6 +1031,7 @@ QByteArray ScriptServer::fileSave(QByteArray&command, QLocalSocket* s, ObjectSto
return handleResponse("Done",s);
}

/*
QByteArray ScriptServer::editableVectorSetBinaryArray(QByteArray&command, QLocalSocket* s, ObjectStore*) {
command.replace("EditableVector::setBinaryArray(","");
Expand Down Expand Up @@ -1058,6 +1071,7 @@ QByteArray ScriptServer::editableVectorSetBinaryArray(QByteArray&command, QLocal
s->waitForBytesWritten(-1);
return "Done.";
}
*/

QByteArray ScriptServer::editableMatrixSetBinaryArray(QByteArray &command, QLocalSocket *s, ObjectStore *_store)
{
Expand Down Expand Up @@ -1104,6 +1118,7 @@ QByteArray ScriptServer::editableMatrixSetBinaryArray(QByteArray &command, QLoca
return "Done.";
}

/*
QByteArray ScriptServer::editableVectorSet(QByteArray&command, QLocalSocket* s, ObjectStore* _store) {
command.remove(0,20); //editableVectorSet(
Expand Down Expand Up @@ -1157,6 +1172,7 @@ QByteArray ScriptServer::vectorGetBinaryArray(QByteArray&command, QLocalSocket*
}
return "Data sent via handleResponse(...)";
}
*/

QByteArray ScriptServer::matrixGetBinaryArray(QByteArray&command, QLocalSocket* s, ObjectStore*) {

Expand Down
10 changes: 5 additions & 5 deletions src/libkstapp/scriptserver.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public slots:
QByteArray newGeneratedVector(QByteArray& command, QLocalSocket* s,ObjectStore*_store);

QByteArray getEditableVectorList(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
QByteArray newEditableVectorAndGetHandle(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
QByteArray newEditableVector(QByteArray& command, QLocalSocket* s,ObjectStore*_store);

QByteArray getMatrixList(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
QByteArray newDataMatrix(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
Expand All @@ -82,7 +82,7 @@ public slots:
QByteArray newEquation(QByteArray& command, QLocalSocket* s,ObjectStore*_store);

QByteArray getHistogramList(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//QByteArray newHistogram(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
QByteArray newHistogram(QByteArray& command, QLocalSocket* s,ObjectStore*_store);

QByteArray getSpectrumList(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
QByteArray newSpectrum(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
Expand Down Expand Up @@ -168,16 +168,16 @@ public slots:


// Hacks
QByteArray editableVectorSetBinaryArray(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//QByteArray editableVectorSetBinaryArray(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//EditableVector::setBinaryArray(

QByteArray editableMatrixSetBinaryArray(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//EditableMatrix::setBinaryArray(

QByteArray editableVectorSet(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//QByteArray editableVectorSet(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//EditableVector::set(

QByteArray vectorGetBinaryArray(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//QByteArray vectorGetBinaryArray(QByteArray& command, QLocalSocket* s,ObjectStore*_store);
//Vector::getBinaryArray(

QByteArray matrixGetBinaryArray(QByteArray& command, QLocalSocket*s,ObjectStore*_store);
Expand Down
138 changes: 135 additions & 3 deletions src/libkstmath/dataobjectscriptinterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,7 @@ SpectrumSI::SpectrumSI(PSDPtr psd) {
_fnMap.insert("interpolateOverHoles",&SpectrumSI::interpolateOverHoles);

_fnMap.insert("setInputVector",&SpectrumSI::setInputVector);
_fnMap.insert("setInputScalar",&SpectrumSI::setInputScalar);
_fnMap.insert("outputVector",&SpectrumSI::outputVector);
_fnMap.insert("outputScalar",&SpectrumSI::outputScalar);

}

Expand Down Expand Up @@ -435,7 +433,7 @@ QString SpectrumSI::gaussianSigma(QString &) {

QString SpectrumSI::outputTypeIndex(QString &) {
if (_psd) {
return QString::number(int(_psd->output()));
return QString::number(int(_psd->output()));
} else {
return "Invalid";
}
Expand All @@ -454,4 +452,138 @@ QString SpectrumSI::interpolateOverHoles(QString &) {
}


/***************************/
/* HistogramSI */
/***************************/
HistogramSI::HistogramSI(HistogramPtr histogram) {
if (histogram) {
_histogram = histogram;
_dataObject = histogram;
} else {
_histogram = 0;
_dataObject = 0;
}

_fnMap.insert("change",&HistogramSI::change);

_fnMap.insert("xMin",&HistogramSI::xMin);
_fnMap.insert("xMax",&HistogramSI::xMax);
_fnMap.insert("nBins",&HistogramSI::nBins);
_fnMap.insert("normalizationType",&HistogramSI::normalizationType);
_fnMap.insert("autoBin",&HistogramSI::autoBin);

_fnMap.insert("setInputVector",&SpectrumSI::setInputVector);
_fnMap.insert("outputVector",&SpectrumSI::outputVector);
}

bool HistogramSI::isValid() {
return _histogram;
}

QByteArray HistogramSI::endEditUpdate() {
if (_histogram) {
_histogram->registerChange();
UpdateManager::self()->doUpdates(true);
UpdateServer::self()->requestUpdateSignal();

return ("Finished editing "%_histogram->Name()).toLatin1();
} else {
return ("Finished editing invalid histogram");
}
}

QString HistogramSI::doCommand(QString command_in) {
if (isValid()) {

QString command = command_in.left(command_in.indexOf('('));

HistogramInterfaceMemberFn fn=_fnMap.value(command,&HistogramSI::noSuchFn);

if(fn!=&HistogramSI::noSuchFn) {
return CALL_MEMBER_FN(*this,fn)(command_in);
}

QString v=doNamedObjectCommand(command_in, _histogram);
if (!v.isEmpty()) {
return v;
}

return "No such command";
} else {
return "Invalid";
}
}

ScriptInterface* HistogramSI::newHistogram(ObjectStore *store) {
HistogramPtr histogram = store->createObject<Histogram>();

return new HistogramSI(histogram);
}

QString HistogramSI::change(QString& command) {
if (_histogram) {
QStringList vars = getArgs(command);

QString vec_name = vars.at(0);
VectorPtr vector = kst_cast<Vector>(_dataObject->store()->retrieveObject(vec_name));


_histogram->change(vector,
vars.at(1).toDouble(), // xmin
vars.at(2).toDouble(), // xmax
vars.at(3).toInt(), // nbins
Histogram::NormalizationType(vars.at(4).toInt()), // normalization type
(vars.at(5).toLower() == "true") // real time autobin
);

return "done";
} else {
return "Invalid";
}
}

QString HistogramSI::xMin(QString &) {
if (_histogram) {
return QString::number(double(_histogram->xMin()));
} else {
return "Invalid";
}
}

QString HistogramSI::xMax(QString &) {
if (_histogram) {
return QString::number(double(_histogram->xMax()));
} else {
return "Invalid";
}
}

QString HistogramSI::nBins(QString &) {
if (_histogram) {
return QString::number(int(_histogram->numberOfBins()));
} else {
return "Invalid";
}
}

QString HistogramSI::normalizationType(QString &) {
if (_histogram) {
return QString::number(int(_histogram->normalizationType()));
} else {
return "Invalid";
}
}

QString HistogramSI::autoBin(QString &) {
if (_histogram) {
if (_histogram->realTimeAutoBin()) {
return "True";
} else {
return "False";
}
} else {
return "Invalid";
}
}

}
32 changes: 32 additions & 0 deletions src/libkstmath/dataobjectscriptinterface.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include "basicplugin.h"
#include "equation.h"
#include "psd.h"
#include "histogram.h"
#include "objectstore.h"
#include "updatemanager.h"
#include "updateserver.h"
Expand Down Expand Up @@ -135,5 +136,36 @@ class KSTMATH_EXPORT SpectrumSI : public DataObjectSI
};


class HistogramSI;
typedef QString (HistogramSI::*HistogramInterfaceMemberFn)(QString& command);

class KSTMATH_EXPORT HistogramSI : public DataObjectSI
{
Q_OBJECT
public:
explicit HistogramSI(HistogramPtr histogram);
QString doCommand(QString);
bool isValid();
QByteArray endEditUpdate();

static ScriptInterface* newHistogram(ObjectStore *store);

protected:
QString noSuchFn(QString&) {return ""; }

private:
HistogramPtr _histogram;

QMap<QString,HistogramInterfaceMemberFn> _fnMap;

QString change(QString &command);
QString xMin(QString &);
QString xMax(QString &);
QString nBins(QString &);
QString normalizationType(QString &);
QString autoBin(QString &);
};


}
#endif // DATAOBJECTSCRIPTINTERFACE_H
5 changes: 5 additions & 0 deletions src/libkstmath/histogram.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include "dialoglauncher.h"
#include "datacollection.h"
#include "objectstore.h"
#include "dataobjectscriptinterface.h"

namespace Kst {

Expand Down Expand Up @@ -120,6 +121,10 @@ Histogram::~Histogram() {
}


ScriptInterface* Histogram::createScriptInterface() {
return new HistogramSI(this);
}

void Histogram::internalUpdate() {

writeLockInputsAndOutputs();
Expand Down
4 changes: 3 additions & 1 deletion src/libkstmath/histogram.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class KSTMATH_EXPORT Histogram : public DataObject {
Q_OBJECT

public:
enum NormalizationType { Number, Percent, Fraction, MaximumOne};
enum NormalizationType { Number=0, Percent, Fraction, MaximumOne};

public:
static const QString staticTypeString;
Expand Down Expand Up @@ -94,6 +94,8 @@ class KSTMATH_EXPORT Histogram : public DataObject {
NormalizationType new_norm_in,
bool realTimeAutoBin = false);

ScriptInterface* createScriptInterface();

protected:
Histogram(ObjectStore *store);
virtual ~Histogram();
Expand Down