Example #1
0
 def set_time(self, t):
     """Moves the position line according to the requested point in time"""
     self.t = t
     idx = csutil.find_nearest_val(
         self.document.data['0:t'].data, t, seed=self.idx)
     logging.debug('Setting time t')
     self.set_idx(idx)
 def set_time(self, t):
     """Changes current values to requested time `t`"""
     if '0:t' in self.doc.data:
         idx = find_nearest_val(self.doc.data['0:t'].data, t, seed=self.idx)
         logging.debug('Setting time t', t, idx)
         self.set_idx(idx)
         return True
     return False
Example #3
0
 def _get_time_idx(self, t):
     # If requested time is bigger than last entry, return -1 index
     if t > self.info[2]:
         #           print('Bigger time', self.info)
         return -1
     # bisect search using self._time handler
     i = csutil.find_nearest_val(self, t, get=self._time)
     return i
Example #4
0
 def set_time(self, t):
     """Moves the position line according to the requested point in time"""
     self.t = t
     idx = csutil.find_nearest_val(self.document.data['0:t'].data,
                                   t,
                                   seed=self.idx)
     logging.debug('Setting time t')
     self.set_idx(idx)
Example #5
0
 def move_line_temp(self):
     """Index line was moved on temperature-based plot"""
     rel = self.move_line('/temperature/temp')
     # Convert relative position with respect to temperature to a time value
     # (cooling ramps will be discarted)
     idx = csutil.find_nearest_val(
         self.document.data['0:kiln/T'].data, rel, seed=self.idx)
     t = self.document.data['0:t'].data[idx]
     self.emit(QtCore.SIGNAL('move_line(float)'), t)
Example #6
0
 def move_line_temp(self):
     """Index line was moved on temperature-based plot"""
     rel = self.move_line('/temperature/temp')
     # Convert relative position with respect to temperature to a time value
     # (cooling ramps will be discarted)
     idx = csutil.find_nearest_val(self.document.data['0:kiln/T'].data,
                                   rel,
                                   seed=self.idx)
     t = self.document.data['0:t'].data[idx]
     self.emit(QtCore.SIGNAL('move_line(float)'), t)
Example #7
0
def find_max_heating_rate(T, rateLimit, maxHeatingRate=80):
    """Find maximum heating rate for temperature `T` using `rateLimit` table and a default of `maxHeatingRate`"""
    if not len(rateLimit):
        return maxHeatingRate
    i = find_nearest_val(rateLimit, T, lambda i: rateLimit[i][0])
    rT, rR = rateLimit[i]
    # If returning a lower T entry, take next limit
    if rT < T:
        if len(rateLimit) > i + 1:
            rT, maxHeatingRate = rateLimit[i + 1]
    elif rT >= T:
        maxHeatingRate = rR
    return maxHeatingRate
Example #8
0
def find_max_heating_rate(T, rateLimit, maxHeatingRate=80):
    """Find maximum heating rate for temperature `T` using `rateLimit` table and a default of `maxHeatingRate`"""
    if not len(rateLimit):
        return maxHeatingRate
    i = find_nearest_val(rateLimit, T, lambda i: rateLimit[i][0])
    rT, rR = rateLimit[i]
    # If returning a lower T entry, take next limit
    if rT < T:
        if len(rateLimit) > i + 1:
            rT, maxHeatingRate = rateLimit[i + 1]
    elif rT >= T:
        maxHeatingRate = rR
    return maxHeatingRate
    def set_idx(self, t):
        if self.paused:
            return False
        logging.debug('DocumentModel.set_idx', t)
        # TODO: convert to time index
        tds = self.doc.data.get('t', False)
        if tds is False:
            return False
        n = find_nearest_val(tds.data, t)
        self.idx = n
# 		self.emit(QtCore.SIGNAL('dataChanged(QModelIndex,QModelIndex)'),self.index(0,1),self.index(n,1))
        self.emit(QtCore.SIGNAL('modelReset()'))
        return True
Example #10
0
def export(sh,
           frame='/hsm/sample0/frame',
           T='/kiln/T',
           output='output.avi',
           framerate=50.0,
           fourcc=default_fourcc,
           prog=False,
           acquisition_start_temperature=20,
           Tstep=0,
           tstep=0,
           centerx=False,
           centery=False):
    """Base video export function"""
    if cv is False:
        logging.debug('No OpenCV library')
        return False
    if not output.lower().endswith('.avi'):
        output += '.avi'

    nT = sh.col(T, raw=True)
    tT = nT.cols.t
    vT = nT.cols.v

    roi = frame.split('/')[:-1]
    roi.append('roi')
    roi = '/'.join(roi)
    roi = sh.col(roi, raw=True)
    x = roi.cols.x
    y = roi.cols.y
    w = roi.cols.w
    h = roi.cols.h
    # Translate to 0
    x_translation = min(x)
    y_translation = min(y)
    x -= x_translation
    y -= y_translation
    print 'translations', x_translation, y_translation
    # Max dimension (video resolution)
    wMax = int(max(x + w))
    hMax = int(max(y + h))
    out = cv.VideoWriter(output, fourcc, framerate, (wMax, hMax))
    ref = reference.get_node_reference(sh, frame)
    N = sh.len(frame)

    index_acquisition_T = csutil.find_nearest_val(
        vT, acquisition_start_temperature, seed=0)
    i = i0 = csutil.find_nearest_val(ref,
                                     tT[index_acquisition_T],
                                     seed=0,
                                     get=lambda i: ref[i][0])
    ti = 0
    if prog:
        prog.setMaximum(N - i)
    pg = 0
    while i < N:
        # Get image
        t, img = ref[i]
        # 		print 'exporting {:.2f} {} {:.0f}'.format(100.*i/N,i,t)
        if isinstance(ref, reference.Binary):
            im = cv.imdecode(np.frombuffer(img, dtype='uint8'), 1)
        elif isinstance(ref, reference.Profile) or isinstance(
                ref, reference.CumulativeProfile):
            # Blank image
            im = np.ones((hMax, wMax), np.uint8) * 255
            # Color black area contained in path
            ((w, h), x, y) = img
            x -= x_translation
            y -= y_translation
            if centerx:
                x += np.uint16(wMax / 2. - int(x.mean()))
            if centery:
                y += np.uint16(hMax / 2. - int(y.mean()))
            # Avoid black-white inversion
            x = np.concatenate(([0, 0], x, [wMax, wMax, 0]))
            y = np.concatenate(([hMax, y[0]], y, [y[-1], hMax, hMax]))
            p = np.array([x, y], np.int32).transpose()
            cv.fillPoly(im, [p], 0)
            m = im.mean()
            if m == 255 or m == 0:
                print 'invalid frame', p
                import pylab
                pylab.plot(x, y)
                pylab.show()
                break
            im = np.dstack((im, im, im))
        else:
            logging.debug('Unsupported reference')
            break
        # Get T
        ti = csutil.find_nearest_val(tT, t, seed=ti)
        Ti = vT[ti]
        cv.putText(im,
                   "T: {:.1f}C".format(Ti), (10, hMax - 10),
                   fontFace=cv.FONT_HERSHEY_DUPLEX,
                   fontScale=1,
                   color=(0, 0, 255))

        # Write frame
        out.write(im)
        # Calculate next frame
        nt = -1
        if Tstep > 0:
            Ti += Tstep
            j = csutil.find_nearest_val(vT, Ti, seed=ti)
            if j <= i:
                Tstep *= -1
                logging.debug('Inverting search direction', Tstep)
                Ti += 2 * Tstep
                j = csutil.find_nearest_val(vT, Ti, seed=ti)
                if j <= i:
                    logging.debug('No more temperature rise', Tstep)
                    break
            nt = tT[j]
        elif tstep > 0:
            nt = tT[ti] + tstep

        # Get frame index at time nt
        if nt > 0:
            j = ref.get_time(nt)
            if j <= i:
                break
            i = j
        else:
            # just take next frame
            i += 1
        if prog:
            QtGui.qApp.processEvents()
            if pg > 1 and prog.value() == 0:
                logging.debug('Export cancelled at frame', i)
                break
            pg = i - i0
            prog.setValue(pg)

    logging.debug('releasing', output)
    out.release()
    return True
    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

        ds = self.doc.data[fields['d']]
        Ts = self.doc.data[fields['T']]
        # Convert to percent, if possible
        self.inidim = getattr(ds, 'm_initialDimension', False)
        if not getattr(ds, 'm_percent', False):
            if self.inidim:
                ds = units.percent_conversion(ds, 'To Percent', auto=False)
        T = Ts.data
        # Cut away any cooling
        while max(T) != T[-1]:
            i = np.where(T == max(T))[0]
            T = T[:i]
        d = ds.data[:len(T)]

        # Standard
        sT, sd = standards[fields['std']]
        # Find start/end T
        start = max(sT[0], T[0]) + fields['start']
        end = min(sT[-1], T[-1]) - fields['end']
        # Cut datasets
        si = find_nearest_val(T, start, get=T.__getitem__)
        ei = find_nearest_val(T, end, get=T.__getitem__)
        logging.debug('Cutting', si, ei)
        T = T[si:ei]
        d = d[si:ei]
        logging.debug('T start, end', start, end)
        f = InterpolatedUnivariateSpline(sT, sd, k=2)
        s0 = f(T[0])
        s_slope = (f(T[-1]) - s0) / (T[-1] - T[0])  # Standard slope
        self.f = f
        self.s_slope = s_slope

        # Just use to get linearity residuals
        (quad, slope, const), res, rank, sing, rcond = np.polyfit(T,
                                                                  d,
                                                                  2,
                                                                  full=True)
        self.quad = quad
        z_slope = (d[-1] - d[0]) / (T[-1] - T[0])  # Sample slope
        z_const = ds.data[0]
        res = np.sqrt(res[0] / len(T))
        # Convert from percentage to micron
        um = res * self.inidim / 100
        factor = s_slope / z_slope
        micron = u'\u03bcm'
        msg = _(
            'Calibration factor: {} \nStandard deviation: \n    {} %\n    {} {}'
        ).format(factor, res, um, micron)
        self.msg = msg
        self.slope, self.const = slope, const
        self.fld, self.ds, self.T, self.d, self.sT, self.sd = fields, ds, T, d, sT, sd
        self.factor, self.res, self.um = factor, res, um
        if fields['label']:
            self.label()
        if fields['add']:
            self.add_datasets(si, d[0])
        self.apply_ops()
        self.doc.model.refresh()
        return factor, res
    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

        ds = self.doc.data[fields['d']]
        Ts = self.doc.data[fields['T']]
        # Convert to percent, if possible
        self.inidim = getattr(ds, 'm_initialDimension', False)
        if not getattr(ds, 'm_percent', False):
            if self.inidim:
                ds = units.percent_conversion(ds, 'To Percent', auto=False)
        T = Ts.data
        # Cut away any cooling
        while max(T) != T[-1]:
            i = np.where(T == max(T))[0]
            T = T[:i]
        d = ds.data[:len(T)]

        # Standard
        sT, sd = standards[fields['std']]
        # Find start/end T
        start = max(sT[0], T[0]) + fields['start']
        end = min(sT[-1], T[-1]) - fields['end']
        # Cut datasets
        si = find_nearest_val(T, start, get=T.__getitem__)
        ei = find_nearest_val(T, end, get=T.__getitem__)
        logging.debug( 'Cutting', si, ei)
        T = T[si:ei]
        d = d[si:ei]
        logging.debug('T start, end', start, end)
        f = InterpolatedUnivariateSpline(sT, sd, k=2)
        s0 = f(T[0])
        s_slope = (f(T[-1]) - s0) / (T[-1] - T[0]) # Standard slope
        self.f = f
        self.s_slope = s_slope

        # Just use to get linearity residuals
        (quad, slope, const), res, rank, sing, rcond = np.polyfit(
            T, d, 2, full=True)
        self.quad = quad
        z_slope = (d[-1] - d[0]) / (T[-1] - T[0]) # Sample slope
        z_const = ds.data[0]
        res = np.sqrt(res[0] / len(T))
        # Convert from percentage to micron
        um = res * self.inidim / 100
        factor = s_slope / z_slope
        micron = u'\u03bcm'
        msg = _('Calibration factor: {} \nStandard deviation: \n    {} %\n    {} {}').format(
            factor, res, um, micron)
        self.msg = msg
        self.slope, self.const = slope, const
        self.fld, self.ds, self.T, self.d, self.sT, self.sd = fields, ds, T, d, sT, sd
        self.factor, self.res, self.um = factor, res, um
        if fields['label']:
            self.label()
        if fields['add']:
            self.add_datasets(si, d[0])
        self.apply_ops()
        self.doc.model.refresh()
        return factor, res
Example #13
0
def export(sh, frame='/hsm/sample0/frame',
           T='/kiln/T',
           output='output.avi',
           framerate=50.0,
           fourcc=default_fourcc,
           prog=False,
           acquisition_start_temperature=20):
    """Base video export function"""
    if cv is False:
        logging.debug('No OpenCV library')
        return False
    if not output.lower().endswith('.avi'):
        output += '.avi'
    if T:
        nT = sh.col(T, raw=True)
        tT = nT.cols.t
        vT = nT.cols.v
    roi = frame.split('/')[:-1]
    roi.append('roi')
    roi = '/'.join(roi)
    roi = sh.col(roi, raw=True)
    x = roi.cols.x
    y = roi.cols.y
    w = roi.cols.w
    h = roi.cols.h
    # Translate to 0
    x_translation = min(x)
    y_translation = min(y)
    x -= x_translation
    y -= y_translation
    print 'translations', x_translation, y_translation
    # Max dimension (video resolution)
    wMax = int(max(x + w))
    hMax = int(max(y + h))
    out = cv.VideoWriter(output, fourcc, framerate, (wMax, hMax))
    ref = reference.get_node_reference(sh, frame)
    N = sh.len(frame)
    
    index_acquisition_T = csutil.find_nearest_val(vT, acquisition_start_temperature, seed=0)
    i = i0 = csutil.find_nearest_val(ref,
                                tT[index_acquisition_T],
                                seed=0,
                                get=lambda i: ref[i][0])
    ti = 0
    if prog:
        prog.setMaximum(N-i)

    while i < N:
        # Get image
        t, img = ref[i]
# 		print 'exporting {:.2f} {} {:.0f}'.format(100.*i/N,i,t)
        if isinstance(ref, reference.Binary):
            im = cv.imdecode(np.frombuffer(img, dtype='uint8'), 1)
        elif isinstance(ref, reference.Profile) or isinstance(ref, reference.CumulativeProfile):
            # Blank image
            im = np.ones((hMax, wMax), np.uint8) * 255
            # Color black area contained in path
            ((w, h), x, y) = img
            x -= x_translation
            y -= y_translation
            # Avoid black-white inversion
            x = np.concatenate(([0,       0], x, [wMax,  wMax,    0]))
            y = np.concatenate(([hMax, y[0]], y, [y[-1], hMax, hMax]))
            p = np.array([x, y], np.int32).transpose()
            cv.fillPoly(im, [p], 0)
            m = im.mean() 
            if m==255 or m==0:
                print 'invalid frame',p
                import pylab
                pylab.plot(x,y)
                pylab.show()
                break
            im = np.dstack((im, im, im))
        else:
            logging.debug('Unsupported reference')
            break
        # Get T
        ti = csutil.find_nearest_val(tT, t, seed=ti)
        cv.putText(im, "T: {:.1f}C".format(
            vT[ti]), (10, hMax - 10), fontFace=cv.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255))
        # Write frame
        out.write(im)
        i += 1
        if prog:
            QtGui.qApp.processEvents()
            if i > 1 and prog.value() == 0:
                logging.debug('Export cancelled at frame', i)
                break
            prog.setValue(i-i0)

    logging.debug('releasing', output)
    out.release()
    return True