コード例 #1
0
 def create_graph(self, graph):
     """Create page and graph if missing"""
     try:
         self.doc.resolveFullWidgetPath(graph)
         logging.debug('GRAPH OK', graph)
         return False
     except:
         pass
     logging.debug('GRAPH MISSING', graph)
     vgraph = graph.split('/')
     page = vgraph[1][:-2]
     has_grid = vgraph[-2] == 'grid'
     logging.debug('MakeDefaultPlot', page, has_grid, graph)
     istime = graph.endswith('/time') or graph.endswith('_time')
     istemp = graph.endswith('/temp') or graph.endswith('_temp')
     self.ops.append(
         document.OperationToolsPlugin(
             MakeDefaultDoc(), {
                 'title': self.fields.get('title', ''),
                 'page': page,
                 'time': istime,
                 'temp': istemp,
                 'grid': has_grid
             }))
     self.apply_ops()
     logging.debug('Done create_graph', graph)
     return True
コード例 #2
0
    def arrange(self, graphics_names, plotted_dataset_names=False):
        arrange_fields = {
            'currentwidget': '/time/time',
            'dataset': 'Line Color',
            'sample': 'Line Style',
            'space': True,
            'plotted_dataset_names': plotted_dataset_names
        }

        for gname in graphics_names:
            arrange_fields['currentwidget'] = gname
            self.ops.append(
                document.OperationToolsPlugin(ArrangePlugin(),
                                              arrange_fields.copy()))

        self.apply_ops('PlotDataset: Arrange')
コード例 #3
0
def runPlugin(window, doc, plugin, fields):
    """Execute a plugin.
    window - parent window
    doc - veusz document
    plugin - plugin object."""

    if isinstance(plugin, plugins.ToolsPlugin):
        mode = 'tools'
    elif isinstance(plugin, plugins.DatasetPlugin):
        mode = 'dataset'
    else:
        raise RuntimeError("Invalid plugin class")

    # use correct operation class for different plugin types
    if mode == 'tools':
        op = document.OperationToolsPlugin(plugin, fields)
    elif mode == 'dataset':
        # a bit of a hack as we don't give currentwidget to this plugin
        del fields['currentwidget']
        op = document.OperationDatasetPlugin(plugin, fields)

    resultstext = ''
    qt4.QApplication.setOverrideCursor(qt4.QCursor(qt4.Qt.WaitCursor))
    try:
        results = doc.applyOperation(op)

        # evaluate datasets using plugin to check it works
        if mode == 'dataset':
            op.validate()
            resultstext = _('Created datasets: ') + ', '.join(results)
        else:
            resultstext = _('Done')

    except (plugins.ToolsPluginException, plugins.DatasetPluginException), ex:
        # unwind operations
        op.undo(doc)
        qt4.QApplication.restoreOverrideCursor()

        qt4.QMessageBox.warning(window,
                                _("Error in %s") % plugin.name, unicode(ex))
コード例 #4
0
    def auto_percent(self, ds, dsn, gname, ax_name):
        """Find if the dataset ds should be converted to percentage based on other datasets sharing the same Y ax."""
        g = self.doc.resolveFullWidgetPath(gname)
        tree = get_plotted_tree(g)
        dslist = tree['axis'].get(g.path + '/' + ax_name, [])

        is_derived = getattr(ds, 'ds', ds)
        is_derived = isinstance(is_derived, document.datasets.Dataset1DPlugin)
        if is_derived:
            ds.m_initialDimension = getattr(ds.parent.ds, 'm_initialDimension',
                                            None)

        pc = getattr(ds, 'm_percent', None)
        if pc is None:
            logging.debug('No m_percent attribute defined', dsn)
            return False

        cvt = None
        for nds in dslist:
            if nds == dsn:
                continue  # itself
            cvt = getattr(self.doc.data[nds], 'm_percent', None)
            if cvt is not None:
                break
        if cvt is None or cvt == pc:
            return False
        # A conversion should happen
        logging.debug('CONVERTING', cvt, pc)
        self.ops.append(
            document.OperationToolsPlugin(PercentPlugin.PercentPlugin(), {
                'ds': dsn,
                'propagate': False,
                'action': 'Invert',
                'auto': False
            }))
        return True
コード例 #5
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
        """
        self.ops = []
        self.doc = interface.document
        # raise DatasetPluginException if there are errors
        ds = interface.document.data.get(fields['ds'], False)
        if not ds:
            raise plugins.DatasetPluginException('Dataset not found' +
                                                 fields['ds'])
        if isinstance(ds, document.datasets.Dataset1DPlugin):
            logging.error(
                'Cannot convert to percent a derived dataset. Please convert the source.'
            )
            return False

        action = units.percent_action(ds, fields['action'])
        ds1 = units.percent_conversion(ds, action, fields['auto'])
        ds = ds1
        self.ops.append(document.OperationDatasetSet(fields['ds'], ds))
        #self.ops.append(document.OperationDatasetSetVal(fields['ds'], 'data',slice(None,None),ds1.data[:]))

        self.apply_ops()
        logging.debug('Converted %s %s using initial dimension %.2f.' %
                      (fields['ds'], fields['action'], ds.m_initialDimension))
        # 		QtGui.QMessageBox.information(None,'Percentage output',
        # 				'Converted %s %s using initial dimension %.2f.' % (fields['ds'], msg, ds.m_initialDimension))

        # updating all dependent datapoints
        convert_func = units.percent_func(ds, action, fields['auto'])
        utils.convert_datapoint_units(convert_func, fields['ds'], self.doc)

        if not fields['propagate']:
            return
        # Find all datasets plotted with the same Y axis
        cvt = []
        tree = get_plotted_tree(self.doc.basewidget)
        upax = []
        for axp, dslist in tree['axis'].iteritems():
            if not fields['ds'] in dslist:
                continue
            logging.debug('Propagating to', cvt)
            cvt += dslist
            upax.append(axp)
        cvt = list(set(cvt))
        if fields['ds'] in cvt:
            cvt.remove(fields['ds'])
        act = 'To Percent' if ds.m_percent else 'To Absolute'
        # Create a non-propagating percentage operation for each dataset found
        for nds in cvt:
            ncur = getattr(self.doc.data[nds], 'm_percent', None)
            if ncur == ds.m_percent:
                continue
            logging.debug('Really propagating percentage to', nds)
            fields = {
                'ds': nds,
                'propagate': False,
                'action': act,
                'auto': True
            }
            self.ops.append(
                document.OperationToolsPlugin(PercentPlugin(), fields))
        # Update axis labels
        old = units.symbols.get(ds.old_unit, False)
        new = units.symbols.get(ds.unit, False)
        if old and new:
            for ax in upax:
                ax = self.doc.resolveFullWidgetPath(ax)
                lbl = ax.settings.label.replace(old, new)
                self.toset(ax, 'label', lbl)
        # Apply everything
        self.apply_ops('Percentage: Propagate')
コード例 #6
0
    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()")
コード例 #7
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
        """
        self.ops = []
        self.doc = interface.document

        ds = interface.document.data.get(fields['ds'], False)
        if not ds:
            raise plugins.DatasetPluginException('Dataset not found' +
                                                 fields['ds'])

        ds1 = units.convert(ds, fields['convert'])
        self.ops.append(document.OperationDatasetSet(fields['ds'], ds1))
        self.apply_ops()

        # Update DataPoints
        convert_func = units.convert_func(ds, fields['convert'])
        utils.convert_datapoint_units(convert_func, fields['ds'], self.doc)

        # Update file-wise time unit if ds is the time dataset
        if ds.linked and fields['ds'] == ds.linked.prefix + 't':
            ds.linked.params.time_unit = ds1.unit

        ####
        # PROPAGATION
        if not fields['propagate']:
            return
        # Find all datasets plotted with the same Y axis
        cvt = []
        tree = get_plotted_tree(self.doc.basewidget)
        upax = []
        for axp, dslist in tree['axis'].iteritems():
            if not fields['ds'] in dslist:
                continue
            logging.debug('Propagating to', cvt)
            cvt += dslist
            upax.append(axp)
        # If time dataset, propagate to all time datasets
        if ds.m_var == 't':
            for k, nds in self.doc.data.iteritems():
                if k == fields['ds']:
                    continue
                if getattr(nds, 'm_var', False) != 't':
                    continue
                cvt.append(k)
        cvt = list(set(cvt))
        # Create a non-propagating unit conversion operation for each dataset
        # found
        for nds in cvt:
            if nds == fields['ds']:
                continue
            ncur = getattr(self.doc.data[nds], 'unit', False)
            if not ncur:
                continue
            logging.debug('Really propagating unit conversion to', nds)
            fields = {
                'ds': nds,
                'propagate': False,
                'convert': fields['convert']
            }
            self.ops.append(
                document.OperationToolsPlugin(UnitsConverterTool(), fields))
        # Update axis labels
        old = units.symbols.get(ds.unit, False)
        new = units.symbols.get(fields['convert'], False)
        if old and new:
            for ax in upax:
                ax = self.doc.resolveFullWidgetPath(ax)
                lbl = ax.settings.label.replace(old, new)
                self.toset(ax, 'label', lbl)

        # Apply everything
        self.apply_ops('UnitsConverterTool: Propagate')
コード例 #8
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 = []
        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()