Writing Plug-ins

A Shape-Link plug-in is a Python script with a class derived from shapelink.ShapeLinkPlugin and some additional meta data. Let’s have a look at this example plugin which prints the rolling mean of a few scalar features to stdout:

 1import shutil
 2
 3import numpy as np
 4
 5from shapelink import ShapeLinkPlugin
 6
 7# We use the terminal width to make sure a line doesn't get cluttered
 8# with prints from a previous line.
 9TERMINAL_WIDTH = shutil.get_terminal_size((80, 20))[0]
10
11
12class RollingMeansPlugin(ShapeLinkPlugin):
13    """Displays a rolling mean of a few scalar features"""
14    def __init__(self, *args, **kwargs):
15        super(RollingMeansPlugin, self).__init__(*args, **kwargs)
16        self.window_size = 100
17        self.scalar_data = {}
18
19    def after_register(self):
20        print(" Preparing for transmission")
21        for feat in self.reg_features.scalars:
22            self.scalar_data[feat] = np.zeros(self.window_size) * np.nan
23
24    def after_transmission(self):
25        print("\n End of transmission\n")
26
27    def choose_features(self):
28        return list()
29
30    def handle_event(self, event_data):
31        """Handle a new event"""
32        window_index = event_data.id % self.window_size
33        for ii, feat in enumerate(self.reg_features.scalars):
34            self.scalar_data[feat][window_index] = event_data.scalars[ii]
35        # print the first three features to stdout
36        msgs = [" Rolling means: "]
37        num_prints = min(3, len(self.reg_features.scalars))
38        for ii in range(num_prints):
39            feat = self.reg_features.scalars[ii]
40            msgs.append("{}: {:.3g}".format(feat,
41                                            np.mean(self.scalar_data[feat])))
42        line = "  ".join(msgs)
43        if len(line) < TERMINAL_WIDTH:
44            line += " " * (TERMINAL_WIDTH - len(line))
45        print(line, end="\r", flush=True)
46
47        return False
48
49
50info = {
51    "class": RollingMeansPlugin,
52    "description": "Display the rolling mean of a few scalar features",
53    "name": "Rolling Means",
54    "version": "0.1.1",
55}

The main action happens in the handle_event function. Your plugin must implement both this function and the choose_features function, which can be used to specify three lists of features (scalar, traces, images). The Verify Aspect Ratio plugin shows how to use the choose_features function. The two functions after_register and after_transmission can be used to set things up (e.g. creation of an additional output file) or to tear things down (e.g. closing that file). Use the __init__ function for defining additional class properties. The info dictionary is required so that the plugin can be run via the Command-line interface.