def __init__(self, showAge=10.0): self.showAge = showAge # window and application will start immediately and run in background self.client = kst.Client("kst_pathPlanning") kstfile = falconspy.FALCONS_CODE_PATH + "/packages/facilities/diagnostics/kst/pathPlanning.kst" # TODO: make relative? # use a tmp file to prevent accidental overwriting if user presses SAVE tmpKstFile = "/tmp/pathPlanning.kst" shutil.copyfile(kstfile, tmpKstFile) self.client.open_kst_file(tmpKstFile) # extract some common-used things (rather than doing it every iteration) self.plotX = self.client.plot('P1') # X plot
def plot_kst(args, chx): llen = len(chx[0]) print("plotting {} {}M points".format(llen, llen / 1e6)) xsam = np.linspace(0, llen, num=llen) client = pykst.Client(args.dirfile[0]) XX = client.new_editable_vector(xsam, name="samples") ix = 0 for f in get_ch_files(args.dirfile[0]): if ch_selected(f, args.chd): YY = client.new_editable_vector(chx[ix].astype(np.float64), name=title(f)) print("adding plot {}".format(f)) client.new_plot().add(client.new_curve(XX, YY)) ix = ix + 1
def figure(): """ Creates a new tab in kst. """ global _client global _current_plot global _subplots if _client is None: _client = kst.Client() _client.new_tab() _current_plot = None _subplots = {}
def plot_data_kst(args, raw_channels): client = pykst.Client("NumpyVector") llen = len(raw_channels[0]) if args.egu == 1: if args.xdt == 0: print( "WARNING ##### NO CLOCK RATE PROVIDED. TIME SCALE measured by system." ) raw_input( "Please press enter if you want to continue with innacurate time base." ) time1 = float(args.the_uut.s0.SIG_CLK_S1_FREQ.split(" ")[-1]) xdata = np.linspace(0, llen / time1, num=llen) else: xdata = np.linspace(0, llen * args.xdt, num=llen) xname = 'time' yu = 'V' xu = 's' else: xname = 'idx' yu = 'code' xu = 'sample' xdata = np.arange(0, llen).astype(np.float64) V1 = client.new_editable_vector(xdata, name=xname) for ch in [int(c) for c in args.pc_list]: channel = raw_channels[ch] ch1 = ch + 1 yu1 = yu if args.egu: try: # chan2volts ch index from 1: channel = args.the_uut.chan2volts(ch1, channel) except IndexError: yu1 = 'code' print("ERROR: no calibration for CH{:02d}".format(ch1)) # label 1.. (human) V2 = client.new_editable_vector(channel.astype(np.float64), name="{}:CH{:02d}".format( re.sub(r"_", r"-", args.uut[0]), ch1)) c1 = client.new_curve(V1, V2) p1 = client.new_plot() p1.set_left_label(yu1) p1.set_bottom_label(xu) p1.add(c1)
def plot_sweep(chanlist, sweepfile = None, client_name = None): """ Quickly plot result of the derived sweep dirfile Inputs: chanlist: list of KIDs, e.g. ['K000','K002'] Looks for fields 'sweep.K000' in 'entry' sweepfile: dirfile, default is latest matching 'yyyymmdd_hhmmss_sweep' client_name: string for title of plot, unique handle default is sweep dirfile name """ if type(chanlist) == str: chanlist = [chanlist] if sweepfile == None: sweepfile = find_lastsweep() if client_name == None: # Client name can't start with number client_name = 'sweep_' + sweepfile[-21:-6] # Load in dirfile and static fields df = gd.dirfile(sweepfile, gd.RDONLY | gd.UNENCODED) lo = df.get_carray('sweep.lo_freqs')/1e6 # MHz bb = df.get_carray('sweep.bb_freqs')/1e6 # MHz client = kst.Client(client_name) client.hide_window() for chan in chanlist: # Find BB freq for this chan - super janky ind = np.int(chan[-3:]) F = client.new_editable_vector(lo + bb[ind]) s21 = df.get_carray('sweep.' + chan) S21 = client.new_editable_vector(10*np.log10(np.abs(s21))) S21.set_name(chan) c1 = client.new_curve(F,S21) p1 = client.new_plot() p1.set_bottom_label('Frequency (MHz)') p1.set_left_label('10*log10(mag)') p1.set_top_label(chan) p1.add(c1) client.show_window() return client
def plot_dirfile_rawfield(myfields, datafile, client_name = None, x_axis = "python_timestamp", fd = None): """ Plot raw fields from a dirfile Inputs: myfield: string for dirfile field, e.g. 'K000_I' Can be a list of strings datafile: dirfile or .txt sourcefile client_name: string for title of plot, unique handle x_axis: python timestamp for human-readability, kst default is "INDEX" (frame count, 1 per packet) fd: frame dict """ if type(myfields) == str: myfields = [myfields] if fd == None: fd = frametype() client = kst.Client(client_name) client.hide_window() X = client.new_data_vector(datafile, field = x_axis, start = fd['start'], num_frames = fd['num_frames'], skip = fd['skip']) for field in myfields: y_axis = field Y = client.new_data_vector(datafile, field = y_axis, start = fd['start'], num_frames = fd['num_frames'], skip = fd['skip']) c1 = client.new_curve(X,Y) p1 = client.new_plot() L1 = client.new_legend(p1) p1.add(c1) check_timestamp(x_axis, p1) client.show_window() return client
def process_data(args): args.chd = {k: 1 for k in list_decode(args.ch)} dir = args.dirfile[0] ch_files = get_ch_files(dir) chx = [ np.fromfile("{}/{}".format(dir, f), dtype='int16') \ for f in ch_files if ch_selected(f, args.chd) ] llen = len(chx[0]) print("plotting {} {}M points".format(llen, llen / 1e6)) xsam = np.linspace(0, llen, num=llen) client = pykst.Client(dir) XX = client.new_editable_vector(xsam, name="samples") ix = 0 for f in ch_files: if ch_selected(f, args.chd): YY = client.new_editable_vector(chx[ix].astype(np.float64), name=title(f)) client.new_plot().add(client.new_curve(XX, YY)) ix = ix + 1
#!/usr/bin/python2.7 import pykst as kst client = kst.Client("RenameDemo") V1 = client.new_data_vector("/home/cbn/programs/KDE/kst_tutorial/gyrodata.dat", field="INDEX", start=0, num_frames=1000) V2 = client.new_data_vector("/home/cbn/programs/KDE/kst_tutorial/gyrodata.dat", field="Column 2", start=0, num_frames=1000) c1 = client.new_curve(V1, V2) p1 = client.new_plot(font_size=12) p1.add(c1) print "-------------- Scalar list -------------" print client.get_scalar_list() print "-------------- Vector list -------------" vectors = client.get_vector_list() print vectors print "----------" # change the name of the vector made from field "Column 1" for Vname in vectors: Vr = client.data_vector(Vname.name())
#!/usr/bin/python2.7 import pykst as kst import numpy as np client = kst.Client("NumpyVector") # create a pair of numpy arrays x = np.linspace(-10, 10, 1000) y = np.sin(x) # copy the numpy arrays into kst and plot them V1 = client.new_editable_vector(x, name="X") V2 = client.new_editable_vector(y, name="sin(X)") c1 = client.new_curve(V1, V2) p1 = client.new_plot() p1.add(c1) V3 = client.new_generated_vector(-10 * 180 / 3.1415926, 10 * 180 / 3.1415926, 100) c2 = client.new_curve(V3, V2) p2 = client.new_plot() p2.add(c2) # print out the name of every vector. vectors = client.get_vector_list() print "----- Vectors: ----------" for vector in vectors: print vector.name() # print out the name of ediable vectors. vectors = client.get_editable_vector_list()
#!/usr/bin/python2.7 import pykst as kst client = kst.Client("TestX2") v1 = client.new_generated_vector(-10, 10, 1000) e1 = client.new_equation(v1, "sin(x)") c1 = client.new_curve(e1.x(), e1.y()) p1 = client.new_plot() p1.add(c1)
import sip sip.setapi('QString', 1) import pykst as kst import sys import random from PyQt4 import QtCore, QtNetwork, QtGui class Magic: def __init__(self, client): self.client = client def test(self): self.client = client random.seed() client.new_circle( (random.random(), random.random()), random.random() / 10.0, "#" + str(random.randint(0, 9)) + str(random.randint(0, 9)) + str(random.randint(0, 9))) client = kst.Client("testbutton") app = QtGui.QApplication(sys.argv) m = Magic(client) s = QtNetwork.QLocalSocket() s.readyRead.connect(m.test) b = kst.Button(client, "Click Here", s, 0.5, 0.5, 0.2, 0.1) app.exec_()
#!/usr/bin/python2.7 # Demonstrate curves, data vectors, equations, spectra, and histograms import pykst as kst client = kst.Client("DataObjects") client.hide_window() # create a 2x2 grid of plots P1 = client.new_plot(font_size=12) P2 = client.new_plot(font_size=12) P3 = client.new_plot(font_size=12) P4 = client.new_plot(font_size=12) client.cleanup_layout(2) # plot a curve made from data vectors dv1 = client.new_data_vector("./demodata.dat", field="INDEX", start=0, num_frames=2000) dv2 = client.new_data_vector("./demodata.dat", field="Column 2", start=0, num_frames=2000) dv3 = client.new_data_vector("./demodata.dat", field="Column 3", start=0, num_frames=2000) c1 = client.new_curve(dv1, dv2)
#!/usr/bin/python2.7 import pykst as kst import time client = kst.Client("PlotLayoutDemo") client.hide_window() #autolayout in tab 1 p1 = client.new_plot() client.new_plot() client.new_plot() client.new_plot() client.new_plot() client.new_plot() client.new_plot() client.new_plot() client.new_plot() client.cleanup_layout(3) client.set_tab_text("First") plots = client.get_plot_list() # do something to every plot for plot in plots: plot.set_top_label(plot.name()) #p1.set_global_font(family = "Courier", font_size = 6)
def subplot(*args, **kwargs): """ Return a subplot axes positioned by the given grid definition. Typical call signature:: subplot(nrows, ncols, plot_number) Where *nrows* and *ncols* are used to notionally split the figure into ``nrows * ncols`` sub-axes, and *plot_number* is used to identify the particular subplot that this function is to create within the notional grid. *plot_number* starts at 1, increments across rows first and has a maximum of ``nrows * ncols``. In the case when *nrows*, *ncols* and *plot_number* are all less than 10, a convenience exists, such that the a 3 digit number can be given instead, where the hundreds represent *nrows*, the tens represent *ncols* and the units represent *plot_number*. For instance:: subplot(211) produces a subaxes in a figure which represents the top plot (i.e. the first) in a 2 row by 1 column notional grid (no grid actually exists, but conceptually this is how the returned subplot has been positioned). .. note:: unlike *matplotlib.pyplot.subplot()*, creating a new subplot with a position which is entirely inside a pre-existing axes will not delete the previous plot. Keyword arguments: *axisbg*: The background color of the subplot, which can be any valid color specifier. """ global _current_plot global _client global _subplots w = 0 h = 0 x = 0 y = 0 n = 0 if (len(args) == 1): h = args[0] / 100 w = (args[0] % 100) / 10 n = args[0] % 10 elif (len(args) == 3): h = args[0] w = args[1] n = args[2] else: w = h = n = 1 x = (n - 1) % w y = (n - 1) / w serial = y + x * 100 + h * 10000 + w * 1000000 #print args[0], w,h,x,y, serial size = (1.0 / w, 1.0 / h) pos = (x / float(w) + 0.5 / w, y / float(h) + 0.5 / h) #print pos, size if serial in _subplots: _current_plot = _subplots[serial] else: if _client is None: _client = kst.Client() _current_plot = _client.new_plot(pos, size) _subplots[serial] = _current_plot if "axisbg" in kwargs: _current_plot.set_fill_color(kwargs["axisbg"])
def plot(*args, **kwargs): """ Plot lines and/or markers to a kst window. *args* is a variable length argument, allowing for multiple *x*, *y* pairs with an optional format string. For example, each of the following is legal:: plot(x, y) # plot x and y using default line style and color plot(x, y, 'bo') # plot x and y using blue circle markers plot(y) # plot y using x as index array 0..N-1 plot(y, 'r+') # ditto, but with red plusses An arbitrary number of *x*, *y*, *fmt* groups can be specified, as in:: a.plot(x1, y1, 'g^', x2, y2, 'g-') By default, each line is assigned a different color in kst. The following format string characters are accepted to control the line style or marker: ================ =============================== character description ================ =============================== ``'-'`` solid line style ``'--'`` dashed line style ``'-.'`` dash-dot line style ``':'`` dotted line style ``'.'`` point marker ``','`` pixel marker ``'o'`` circle marker ``'v'`` triangle_down marker ``'^'`` triangle_up marker ``'s'`` square marker ``'*'`` star marker ``'+'`` plus marker ``'x'`` x marker ``'D'`` diamond marker ================ =============================== The following color abbreviations are supported: ========== ======== character color ========== ======== 'b' blue 'g' green 'r' red 'c' cyan 'm' magenta 'y' yellow 'k' black 'w' white ========== ======== Line styles and colors are combined in a single format string, as in ``'bo'`` for blue circles. The *kwargs* can be used to set the color, the line width, the line type, and the legend label. You can specify colors using full names (``'green'``), or hex strings (``'#008000'``). Some examples:: plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2) plot([1,2,3], [1,4,9], 'rs', label='line 2') axis([0, 4, 0, 10]) legend() If you make multiple lines with one plot command, the kwargs apply to all those lines, e.g.:: plot(x1, y1, x2, y2, linewidth=2) Both lines will have a width of 2. You do not need to use format strings, which are just abbreviations. All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with:: plot(x, y, color='green', linestyle='dashed', marker='o', color='blue', markersize=12). Supported kwargs are:: color label linestyle linewidth markersize """ global _current_plot global _client if _client is None: _client = kst.Client() if _current_plot is None: _current_plot = _client.new_plot() C = _CurveInfo() if "linewidth" in kwargs: C.line_width = kwargs["linewidth"] if "color" in kwargs: C.color = kwargs["color"] if "linestyle" in kwargs: C.line_style = kwargs["linestyle"] if "markersize" in kwargs: C.marker_size = kwargs["markersize"] if "label" in kwargs: C.label = kwargs["label"] for arg in args: if isinstance(arg, basestring): C.f = arg if (C.y is None) & (isinstance(C.x, _np.ndarray)): C.y = C.x C.x = _np.linspace(0, C.y.size - 1, C.y.size) if (isinstance(C.x, _np.ndarray)): _add_curve_to_plot(_current_plot, C) C.reset() else: if (isinstance(C.y, _np.ndarray)): _add_curve_to_plot(_current_plot, C) C.reset() if isinstance(C.x, _np.ndarray): C.y = _np.asanyarray(arg, dtype=_np.float64) else: C.x = _np.asanyarray(arg, dtype=_np.float64) if (C.y is None) & (isinstance(C.x, _np.ndarray)): C.y = C.x C.x = _np.asanyarray([0.0, C.y.size - 1.0], dtype=_np.float64) if (isinstance(C.x, _np.ndarray)): _add_curve_to_plot(_current_plot, C)
text = "" def __init__(self, client): self.client = client self.s = QtNetwork.QLocalSocket() self.s.readyRead.connect(self.create) self.s2 = QtNetwork.QLocalSocket() self.s2.readyRead.connect(self.changeValue) self.l = kst.LineEdit(client, "", self.s2, 0.47, 0.975, 0.93, 0.025) self.b = kst.Button(client, "Go!", self.s, 0.97, 0.975, 0.05, 0.025) self.plot = client.new_plot((0.5, 0.4885), (0.9, 0.8)) self.genVec = client.new_generated_vector(-100, 100, 1000) def create(self): eq = client.new_equation(self.genVec, self.text) c = client.new_curve(eq.x(), eq.y()) self.plot.add(c) def changeValue(self): strx = QtCore.QString(self.s2.read(8000)) if strx.contains("valueSet:"): strx.remove("valueSet:") self.text = str(strx) client = kst.Client() app = QtGui.QApplication(sys.argv) m = KsNspire(client) app.exec_()
#!/usr/bin/python2.7 import pykst as kst client = kst.Client("TestVectors") client.quit()
#!/usr/bin/python2.7 import pykst as kst client = kst.Client("EqHist") v1 = client.new_generated_vector(0, 10, 1000) v4 = client.new_generated_vector(0, 20, 10000) e1 = client.new_equation(v1, "x^2") e1.set_x(v4) v2 = e1.y() v3 = e1.x() print "vector 2 name: ", v2.name() print "vector 2 Value at 4th element: ", v2.value(3) print "vector 1 type: ", v1.type_str() c1 = client.new_curve(e1.x(), e1.y()) c1.set_color("blue") p1 = client.new_plot((0.5, 0.25), (1, 0.5)) p1.add(c1) e2 = client.new_equation(v1, "x^2.1") e2.set_x(v4) c12 = client.new_curve(e2.x(), e2.y()) p1.add(c12) psd1 = client.new_spectrum(e1.x()) c2 = client.new_curve(psd1.x(), psd1.y()) c2.set_color("green")
def plot_dirfile_IQequation(chanlist, datafile, client_name = None, eqnlist = ["mag"], sweepdict = None, sweepfile = None, x_axis = "python_timestamp", fd = None): """ Plot an equation involving IQ for a channel list Inputs: chanlist: list of KIDs, e.g. ['K000','K002'] Looks for fields 'K000_I', 'K000_Q', etc. datafile: dirfile or .txt sourcefile client_name: string for title of plot, unique handle eqn: list of equations or functions of (Ifield, Qfield) usually ["mag","phase","df","x"] sweepdict: dict output from process_sweep, needed for df or x x_axis: python timestamp for human-readability, kst default is INDEX (frame count, 1 per packet) fd: frame dict """ # If single strings for chanlist and eqnlist, turn into lists if type(chanlist) == str: chanlist = [chanlist] if type(eqnlist) == str: eqnlist = [eqnlist] if fd == None: fd = frametype() # If requested df or x and don't have sweepdict, load it if (("df" in eqnlist) or ("x" in eqnlist)): sweepdict = process_sweep(sweepfile) client = kst.Client(client_name) client.hide_window() X = client.new_data_vector(datafile, field = x_axis, start = fd['start'], num_frames = fd['num_frames'], skip = fd['skip']) for chan in chanlist: Ifield = chan + '_I' I = client.new_data_vector(datafile, field = Ifield, start = fd['start'], num_frames = fd['num_frames'], skip = fd['skip']) I.set_name(Ifield) Qfield = chan + '_Q' Q = client.new_data_vector(datafile, field = Qfield, start = fd['start'], num_frames = fd['num_frames'], skip = fd['skip']) Q.set_name(Qfield) for eqn in eqnlist: if (eqn == "df") or (eqn == "x"): eqnstring = equationstring_IQ(eqn, Ifield, Qfield, sweepdict[chan]) else: eqnstring = equationstring_IQ(eqn, Ifield, Qfield) e1 = client.new_equation(X, eqnstring, name = chan + ' ' + eqn) c1 = client.new_curve(e1.x(), e1.y()) p1 = client.new_plot() p1.add(c1) check_timestamp(x_axis, p1) client.show_window() return client
#!/usr/bin/python2.7 import pykst as kst import numpy as np import time client = kst.Client("VectorIO") t0 = time.clock() # create a pair of numpy arrays x = np.linspace(0, 50, 500000) y = np.sin(x) t1 = time.clock() # copy the numpy arrays into kst and plot them V1 = client.new_editable_vector(x) V2 = client.new_editable_vector(y) c1 = client.new_curve(V1, V2) p1 = client.new_plot() p1.add(c1) t2 = time.clock() # copy numpy array back into python. A = V2.get_numpy_array() t3 = time.clock() # manipulate the array in python, and plot it in kst A = A * A
#!/usr/bin/python2.7 import pykst as kst client = kst.Client("viewitems") P1 = client.new_plot((0.25, 0.25), (0.5, 0.5), 0) P1.set_x_range(-10.0, 10.0) P1.set_global_font("courier", 12, False, False) C1 = client.new_circle((0.9, 0.3), 0.1, stroke_width=2, stroke_brush_color="red") C1.set_fill_color("Green") C1.set_diameter(0.05) B1 = client.new_box((0.9, 0.9), (0.1, 0.1), fill_color="pink") E1 = client.new_ellipse((0.1, 0.7), (0.1, 0.1), 45, fill_color="blue") A1 = client.new_arrow((0.1, 0.5), (0.2, 0.8), False, True, 18) A1.set_stroke_style(3) #A1.set_endpoints((0.2, 0.7), (0.05, 0.8)) L1 = client.new_line((0.20, 0.20), (0.30, 0.30), stroke_width=2, stroke_brush_color="green") L1.set_stroke_style(2) L1.set_parent_auto() L1.set_lock_pos_to_data(True)
'''Returns an image of the Mandelbrot fractal of size (h,w). ''' y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ] c = x+y*1j z = c divtime = maxit + np.zeros(z.shape, dtype=np.float64) for i in xrange(maxit): z = z**2 + c diverge = z*np.conj(z) > 2**2 # who is diverging div_now = diverge & (divtime==maxit) # who is diverging now divtime[div_now] = i # note when z[diverge] = 2.0 # avoid diverging too much return divtime client=kst.Client("numpy_matrix_demo") np = mandelbrot(1000,1000) M = client.new_editable_matrix(np) I = client.new_image(M) P = client.new_plot() P.add(I) # print out name and size of all matrixes matrixes = client.get_matrix_list() for matrix in matrixes : print matrix.name(), matrix.width(), matrix.height()