def apply(self, cmd, fields):
        """Do the work of the plugin.
        cmd: veusz command line interface object (exporting commands)
        fields: dict mapping field names to values
        """
        self.ops = []
        self.doc = cmd.document

        c = self.doc.resolveFullWidgetPath(fields['curve'])
        if c is None:
            c = self.doc.resolveFullWidgetPath(fields['currentwidget'])
            if c is None:
                raise plugins.ToolsPluginException(
                    'You should run this tool on a curve')

        g = utils.searchFirstOccurrence(c, 'graph', -1)
        if g is None or g.typename != 'graph':
            logging.debug('found', g, c)
            raise plugins.ToolsPluginException(
                'Error: Curve is not contained in a graph.')
        pts = fields['x']
        ds = self.doc.data.get(pts, False)
        if not ds:
            xds = self.doc.data.get(c.settings.xData, False)
            x = False
            if not xds or not xds.linked:
                pass
            elif c.settings.xData.endswith('T'):
                x = 't'
            elif c.settings.xData.endswith('t'):
                x = 'kiln/T'
            if x:
                if len(xds.linked.prefix):
                    x = xds.linked.prefix + ':' + x
                ds = self.doc.data.get(x, False)
                pts = x

        if not ds:
            raise plugins.ToolsPluginException(
                'Error: Cannot find a proper coloring dataset.')
        # Undo
        if c.settings.Color.points == pts:
            self.toset(c, 'Color/points', '')
            if c.settings.marker == u'circle':
                self.toset(c, 'marker', u'none')
        # Do
        else:
            self.toset(c, 'Color/points', pts)
            if c.settings.marker == u'none':
                self.toset(c, 'marker', u'circle')

        # Ranges
        self.toset(c, 'Color/min', min(ds.data))
        self.toset(c, 'Color/max', max(ds.data))
        self.toset(c, 'MarkerFill/colorMap', 'transblack')
        self.toset(c, 'MarkerFill/transparency', 10)
        self.toset(c, 'MarkerLine/hide', True)

        self.apply_ops()
示例#2
0
    def get_node_configuration(self, node, rule=False):
        p = node.path
        if rule:
            regex = re.compile(rule.replace('\n', '|'))
            if not regex.search(p):
                raise plugins.ToolsPluginException(
                    self._(
                        'The target does not conform to rule {}:\n {}').format(
                            rule, p))
        if not node.linked:
            raise plugins.ToolsPluginException(
                self.
                _('The selected node does not seem to have an associated configuration'
                  ) + p)

        return node.get_configuration()
示例#3
0
 def apply(self, interface, fields):
     """Do the work of the plugin.
     interface: veusz command line interface object (exporting commands)
     fields: dict mapping field names to values
     """
     smp = fields['sample']
     # FIXME: DEPRECATED
     from misura.client import filedata
     if not filedata.ism(smp, filedata.Sample):
         t = str(type(smp))
         raise plugins.ToolsPluginException(
             'The target must be a sample, found: ' + t)
     if filedata.ism(smp.linked, filedata.LinkedMisuraFile):
         raise plugins.ToolsPluginException(
             'misura tests cannot be corrected, as motor movement correction is performed runtime.'
         )
     pass
    def apply(self, cmd, fields):
        """Do the work of the plugin.
        cmd: veusz command line interface object (exporting commands)
        fields: dict mapping field names to values
        """
        logging.debug('ArrangePlugin.apply')
        self.ops = []
        self.cmd = cmd
        self.doc = cmd.document
        self.fields = fields
        if fields['sample'] == fields['dataset']:
            raise plugins.ToolsPluginException(
                'You must choose different markers for Datasets and Samples.')

        unused_formatting_opt = set(defvars.keys()) - set(
            [fields['sample'], fields['dataset']])
        unused_formatting_opt = list(unused_formatting_opt)[0]

        # Search for the graph widget
        gobj = self.doc.resolveFullWidgetPath(fields['currentwidget'])
        gobj = utils.searchFirstOccurrence(gobj, 'graph')
        if gobj is None or gobj.typename != 'graph':
            raise plugins.ToolsPluginException(
                'You should run this tool on a graph')

        graph = gobj.path
        tree = get_plotted_tree(gobj)
        smps = tree['sample']

        # Ax Positioning
        axes, axcolors = self.arrange_axes(tree, graph)
        # Set plot colors based on axis colors
        var, m_var, defvar = defvars[fields['sample']]
        LR, LG, LB = colorLevels(len(smps))
        for plotpath in tree['plot']:
            self.arrange_curve(plotpath, tree, axes, axcolors, var, m_var, LR,
                               LG, LB, unused_formatting_opt)

        self.apply_ops()
示例#5
0
    def apply(self, interface, fields):
        test = fields['test'].linked
        # Horrific!
        from misura.client import filedata
        if not filedata.ism(test, filedata.LinkedMisuraFile):
            raise plugins.ToolsPluginException(
                'The target must be misura test file')
        # Search for test name
        uk = test.prefix + 'unknown'
        kiln = getattr(test.conf, 'kiln', False)
        if not kiln:
            raise plugins.ToolsPluginException('No Kiln configuration found.')
        instr = getattr(test.conf, test.instrument, False)
        if not instr:
            raise plugins.ToolsPluginException(
                'No measure configuration found.')

        sname = instr.measure.desc.get('name', {'current': uk})['current']
        tc = test.prefix + 'tc'
        interface.To('/time/time')
        drawCycleOnGraph(interface, kiln['curve'], label=sname, wdg=tc)
        interface.To('/temperature/temp')
        drawCycleOnGraph(interface, kiln['curve'], label=sname, wdg=tc)
 def label(self):
     """Draw label"""
     cur = self.fld.get('currentwidget')
     g = self.doc.resolveFullWidgetPath(cur)
     g = utils.searchFirstOccurrence(g, ['graph', 'page'])
     if g is None or g.typename not in ['graph', 'page']:
         raise plugins.ToolsPluginException(
             'Impossible to draw the label. Select a page or a graph.')
     name = 'lbl_' + self.fld['d'].replace('summary/', '').replace('/', '_')
     if not g.getChild(name):
         self.ops.append(document.OperationWidgetAdd(g, 'label', name=name))
         self.apply_ops(self.name + ':CreateLabel')
     lbl = g.getChild(name)
     self.toset(lbl, 'label', self.msg.replace('\n', '\\\\'))
    def apply(self, command_interface, fields):
        doc = command_interface.document
        self.doc = doc
        command_interpreter = CommandInterpreter(doc)
        smp_path0 = fields['sample'].path
        smp_path = smp_path0.split(':')[1]
        vsmp = smp_path.split('/')
        smp_name = vsmp[-1]  # sample name
        smp_path = '/' + '/'.join(vsmp)  # cut summary/ stuff
        report_path = '/'+smp_path[1:].replace('/','_')+'_report'
        logging.debug(smp_path, smp_name, report_path)
        test = fields['sample'].linked
        from .. import filedata
        if not filedata.ism(test, filedata.LinkedMisuraFile):
            logging.debug(type(test), test)
            raise plugins.ToolsPluginException(
                'The target must be misura test file')
        # Search for test name
        uk = test.prefix + 'unknown'
        kiln = getattr(test.conf, 'kiln', False)
        if not kiln:
            raise plugins.ToolsPluginException('No Kiln configuration found.')
        instr = getattr(test.conf, test.instrument, False)
        if not instr:
            raise plugins.ToolsPluginException(
                'No measure configuration found.')
            
        # Delete an existing report page to refresh on second run
        try:
            page = doc.resolveFullWidgetPath(report_path)
            op = OperationWidgetDelete(page)
            self.doc.applyOperation(op)
        except:
            pass
        measure = instr.measure
        sample = getattr(instr, smp_name)
        
        tpath = self.templates.get(fields['template_file_name'], False)
        if not tpath:
            d = fields['template_file_name']
        else:
            d = os.path.join(tpath, fields['template_file_name'])
        logo = os.path.join(params.pathArt, 'logo.png')
        tpl = open(d, 'rb').read().replace("u'report'", "u'{}'".format(report_path[1:]))
        command_interpreter.run(tpl)
        
        std = 'm4'
        if 'Standard: Misura 4' in tpl:
            std = 'm4'
        elif 'Standard: Misura 3' in tpl:
            std = 'm3'
        elif 'Standard: CEN/TS' in tpl:
            std = 'cen' 
        
        shapes = shape_names[std]
        
        page = doc.resolveFullWidgetPath(report_path)
        # Substitutions
        tc = kiln['curve']
        if len(tc) <= 8:
            drawCycleOnGraph(command_interface, tc, label=False, wdg=report_path +
                             '/lbl_tc', color='black', size='6pt', create=False)
        else:
            self.toset(page.getChild('lbl_tc'), 'hide', True)
        msg = wr('Measure', measure['name'])
        msg += '\\\\' + wr('Sample', sample['name'])
        self.toset(page.getChild('name'), 'label', msg)

        zt = test.conf['zerotime']
        zd = datetime.date.fromtimestamp(zt)
        dur = datetime.timedelta(seconds=int(measure['elapsed']))
        sdur = '{}'.format(dur)
        msg = wr('Date', zd.strftime("%d/%m/%Y"))
        msg += '\\\\' + wr('Duration', sdur)
        msg += render_meta(measure, inter='\\\\', zt=zt, full=True)
        self.toset(page.getChild('metadata'), 'label', msg)

# 		msg=render_meta(sample,'None')
# 		self.toset(page.getChild('shapes'),'label',msg)

        oname = measure.desc.get('operator', {'current': False})['current']
        if oname:
            self.toset(
                page.getChild('operator'), 'label', wr('Operator', oname))
        self.toset(
            page.getChild('uid'), 'label', wr('UID', measure['uid'], 34))
        self.toset(
            page.getChild('serial'), 'label', wr('Serial', test.conf['eq_sn']))
        self.toset(
            page.getChild('furnace'), 'label', wr('Furnace', kiln['ksn']))
        self.toset(
            page.getChild('logo'), 'filename', logo)

        msg = ''
        
        should_draw_shapes = True
        
        for sh in shapes:
            if not sample.has_key(sh):
                should_draw_shapes = False

        if should_draw_shapes:
            for sh in shapes:
                pt = sample[sh]
                shn = sample.gete(sh)['name']
                if pt['time'] in ['None', None, '']:
                    msg += 'None\\\\'
                    self.toset(page.getChild('lbl_' + sh), 'label', shn + ', ?')
                    continue
                image_reference = {'dataset': smp_path + '/profile',
                                   'filename': test.params.filename,
                                   'target': pt['time']}
                self.dict_toset(page.getChild(sh), image_reference)
                T = '%.2f{{\\deg}}C' % pt['temp']
                self.toset(page.getChild('lbl_' + sh), 'label', shn + ', ' + T)
                msg += T + '\\\\'
            self.toset(page.getChild('shapes'), 'label', msg)

            self.dict_toset(page.getChild('initial'), {'dataset': smp_path + '/profile',
                                                       'filename': test.params.filename, 'target': 0})
            T = doc.data.get(test.prefix + smp_path[1:] + '/T', False)
            if T is False:
                T = doc.data.get(test.prefix + 'kiln/T')
            T = T.data[0]
            self.toset(page.getChild('lbl_initial'), 'label',
                       'Initial, %.2f{{\\deg}}C' % T)

            #self.toset(page.getChild('standard'), 'label', wr(
            #    'Standard', sample['preset'], 50))

        # Thermal cycle plotting
        from ..procedure.thermal_cycle import ThermalCyclePlot
        from ..procedure.model import clean_curve
        graph = report_path + '/tc'
        p0 = test.prefix+sample['fullpath'][1:]
        cf = {'graph': graph, 'xT': p0+'reportxT',
              'yT': p0+'reportyT', 'xR': p0+'reportxR', 'yR': p0+'reportyR'}
        ThermalCyclePlot.setup(command_interface, with_progress=False, topMargin='4.7cm', **cf)
        tc = clean_curve(tc, events=False)
        ThermalCyclePlot.importCurve(command_interface, tc, **cf)
        cf = {'Label/font': 'Bitstream Vera Sans', 'Label/size': '6pt',
              'TickLabels/font': 'Bitstream Vera Sans',
              'TickLabels/size': '6pt'}
        self.dict_toset(doc.resolveFullWidgetPath(graph + '/y'), cf)
        self.dict_toset(doc.resolveFullWidgetPath(graph + '/y1'), cf)

        self.ops.append(document.OperationToolsPlugin(PlotPlugin.PlotDatasetPlugin(),
                                                      {'x': [test.prefix + 'kiln/T'],
                                                       'y': [smp_path0 + '/' + fields['measure_to_plot']],
                                                       'currentwidget': report_path + '/temp'}
                                                      ))
        self.apply_ops()

        self.dict_toset(doc.resolveFullWidgetPath(
            report_path + '/temp/ax:' + fields['measure_to_plot']), cf)

        self.apply_ops()

        command_interpreter.run("MoveToLastPage()")
    def apply(self, cmd, fields):
        """Do the work of the plugin.
        cmd: veusz command line interface object (exporting commands)
        fields: dict mapping field names to values
        """
        self.ops = []
        self.doc = cmd.document
        cur = fields['currentwidget']
        g = self.doc.resolveFullWidgetPath(cur)
        g = utils.searchFirstOccurrence(g, 'graph')
        if g is None or g.typename != 'graph':
            raise plugins.ToolsPluginException(
                'You should run this tool on a graph')
        axn = fields['axis']
        val = fields['val']
        text = fields['text']
        targetds = fields['target']
        doc = cmd.document

        hor = axn == 'X'
        datapoint_paths = []
        logging.debug( 'targets', targetds)
        for datapoint_parent in g.children:
            if not isinstance(datapoint_parent, veusz.widgets.point.PointPlotter):
                continue
            if datapoint_parent.settings.hide:
                logging.debug('Skipping hidden object', datapoint_parent.path)
                continue
            if datapoint_parent.settings.yData not in targetds and len(targetds) > 0:
                logging.debug('Skipping non-targeted object', datapoint_parent.path, 
                              datapoint_parent.settings.yData)
                continue
            # Search the nearest point
            x = datapoint_parent.settings.get('xData').getFloatArray(doc)
            y = datapoint_parent.settings.get('yData').getFloatArray(doc)
            dst = abs(x - val) if hor else abs(y - val)
            i = np.where(dst == dst.min())[0]
            if len(i) == 0:
                raise plugins.ToolsPluginException(
                    'Impossible to find required value: %E' % val)
            i = i[0]
            # Add the datapoint
            cmd.To(g.path)
            name = datapoint_parent.createUniqueName('datapoint')
            lblname = name + '_lbl'

            # Create the datapoint
            datapoint_settings = {'name': name,
                                  'xAxis': datapoint_parent.settings.xAxis,
                                  'yAxis': datapoint_parent.settings.yAxis,
                                  'xPos': float(x[i]),
                                  'yPos': float(y[i]),
                                  'coordLabel': lblname,
                                  'labelText': text,
                                  'search': fields['search'],
                                  'searchRange': fields['searchRange']}

            if fields.has_key('critical_x'):
                datapoint_settings['critical_x'] = fields['critical_x']

            self.ops.append(document.OperationWidgetAdd(datapoint_parent,
                                                        'datapoint',
                                                        **datapoint_settings))

            datapoint_paths.append(datapoint_parent.path + '/' + name)

        logging.debug('Intercepting', self.ops)
        self.apply_ops('Intercept')

        for path in datapoint_paths:
            cmd.To(path)
            cmd.Action('up')
def check_consistency(reference_curve, translating_curve):
    if reference_curve.parent != translating_curve.parent:
        raise plugins.ToolsPluginException(
            'The selected curves must belong to the same graph.')
    def apply(self, cmd, fields):
        """Do the work of the plugin.
        cmd: veusz command line interface object (exporting commands)
        fields: dict mapping field names to values
        """
        self.ops = []
        self.doc = cmd.document
        smpe = fields['sample']
        p = smpe.path
        if '/sample' not in p:
            raise plugins.ToolsPluginException(
                'The target must be a sample or a sample dataset, found: ' + p)
        cur = fields['currentwidget']
        g = self.doc.resolveFullWidgetPath(cur)
        g = utils.searchFirstOccurrence(g, 'graph')
        if g is None or g.typename != 'graph':
            logging.debug('Found graph:', g)
            raise plugins.ToolsPluginException(
                'You should run this tool on a graph')
        logging.debug('ShapesPlugin searching', p)
        cur = g.path
        conf = False
        vds = []
        for k, ent in smpe.children.iteritems():
            conf = getattr(ent.ds, 'm_conf', False)
            if not conf:
                continue
            if len(ent.ds) > 0:
                vds.append(ent.path)
        if not conf or len(vds) == 0:
            raise plugins.ToolsPluginException('No metadata found for ' + p)
        logging.debug('Found datasets', vds)
        smpp = smpe.path.split(':')[-1]
        # Detect if a sample dataset was selected and go up one level
        if smpp.split('/')[-2].startswith('sample'):
            smpp = smpe.parent.path
        smpp = smpp.replace('summary', '')
        logging.debug('Found sample path', smpp, p)
        smp = conf.toPath(smpp)
        logging.debug('config', smp)

        all_items = smp.describe().iteritems()
        sample_shapes = filter(lambda item: item[1]['type'] == 'Meta', all_items)

        required_shapes_filter = standard_filtering_predicates[fields['characteristic_shape_standard']]
        required_sample_shapes = filter(lambda item: required_shapes_filter(item[0]), sample_shapes)

        for shape, opt in required_sample_shapes:
            pt = opt['current']
            t = pt['time']
            T = pt['temp']
            shape_name = str(fields['text']).replace('$shape$', remove_prefix(shape))
            txt = u'%s - %s °C' % (shape_name, pt['temp'])
            if t in [0, None, 'None'] or T in [0, None, 'None']:
                logging.debug('Shape not found:', shape)
                continue
            # Absolute time translations
            if t > conf['zerotime'] / 2:
                logging.debug('Absolute time translation', t, conf['zerotime'])
                t -= conf['zerotime']
            # Temperature plotting
            basename = smpe.path.replace('/', ':') + '_'
            val = T if 'temp' in cur.split('/') else t
            logging.debug('Selected value based on ', shape, cur, val, pt,t, T)
            f = {'currentwidget': cur,
                 'axis': 'X',
                 'val': val,
                 'text': txt,
                 'basename': basename + shape,
                 'target': vds,
                 'search': 'Nearest (Fixed X)',
                 'searchRange': 5
                 }
            self.ops.append(
                document.OperationToolsPlugin(InterceptPlugin(), f))

        logging.debug('ShapesPlugin ops', self.ops)
        self.apply_ops()
示例#11
0
    def apply(self, cmd, fields):
        """Do the work of the plugin.
        cmd: veusz command line interface object (exporting commands)
        fields: dict mapping field names to values
        """
        self.ops = []
        doc = cmd.document
        self.doc = doc
        self.cmd = cmd

        cur = fields['currentwidget']
        g = self.doc.resolveFullWidgetPath(cur)
        g = utils.searchFirstOccurrence(g, 'graph')
        if g is None or g.typename != 'graph':
            raise plugins.ToolsPluginException(
                'You should run this tool on a graph')

        logging.debug('Plotting:', fields['x'], fields['y'])
        cnames = {}
        doc = cmd.document
        t = time()
        gnames = []
        n = 0
        valid_x, valid_y = [], []
        for i, x in enumerate(fields['x']):
            y = fields['y'][i]
            if not (doc.data.has_key(x) and doc.data.has_key(y)):
                continue
            valid_x.append(x)
            valid_y.append(y)
            n += self.validate_datasets((doc.data[x], doc.data[y]))
        if n > 0:
            # TODO: reload document!
            pass

        for i, x in enumerate(valid_x):
            y = valid_y[i]
            logging.debug('plotting value:', y, 'data:', doc.data[y])
            ds = doc.data[y]
            # If the ds is recursively derived, substitute it by its entry
            if not hasattr(ds, 'm_smp'):
                logging.debug('Retrieving ent', y)
                ds = doc.ent.get(y, False)

            # Get the curve and axis name
            cname, ax_name, ax_lbl = dataset_curve_name(ds, y)

            gname = g.path

            self.auto_percent(ds, y, gname, ax_name)

            self.initCurve(name=cname,
                           xData=x,
                           yData=y,
                           yAxis=ax_name,
                           axisLabel=ax_lbl,
                           graph=gname)
            if gname not in gnames:
                gnames.append(gname)
            cnames[y] = cname

        self.apply_ops('PlotDataset: Customize')
        if len(fields) > 0 and len(fields['y']) > 0:
            self.arrange(gnames, fields['y'])

        return cnames