コード例 #1
0
ファイル: _plot.py プロジェクト: depixusgenome/trackanalysis
    def __reset_colors(self, ind:int, xaxis: List[str], stats: pd.DataFrame):
        cnf    = self._model.theme
        dflt   = tohex(cnf.vertices.line_color)
        if not self._model.theme.uselabelcolors or len(stats['x']) == 0:
            stats['color'] = np.full(len(stats['x']), dflt)
            return

        tags = getattr(cnf, xaxis[ind]+"tag", {}) if len(xaxis) else {}
        if tags:
            colors = tohex({
                tags[i]: j for i, j in getattr(cnf, xaxis[ind]+"color", {}).items()
            })
        elif (
                self._model.theme.defaultcolors != 'none'
                and isinstance(stats['x'][0], (list, tuple))
                and len(stats['x'][0]) > 1
        ):
            vals   = [i[ind] for i in stats['x']]
            vals   = sorted(j for i, j in enumerate(vals) if j not in vals[:i])
            colors = palette(self._model.theme.defaultcolors, vals)
        else:
            stats['color'] = np.full(len(stats['x']), dflt)
            return

        if colors and isinstance(stats['x'][0], tuple) and len(stats['x'][0]) > ind:
            stats['color'] = np.array([colors.get(i[ind], dflt) for i in stats['x']])
        elif colors and isinstance(stats['x'][0], str):
            stats['color'] = np.array([colors.get(i,      dflt) for i in stats['x']])
        else:
            stats['color'] = np.full(len(stats['x']), dflt)
コード例 #2
0
    def _beadsdata(self):
        fov = self._fov
        if fov is None:
            return dict(
                data=dict.fromkeys(('x', 'y', 'text', 'color', 'ttips'), []))

        hexes = tohex(self._theme.colors)
        clrs = {
            i: hexes[i]
            for i in ('ok', 'fixed', 'bad', 'discarded', 'missing')
        }
        status = self._status()
        ttips = self._tooltips()
        items = fov.beads
        data = {
            "x": [i.position[0] for i in items.values()],
            "y": [i.position[1] for i in items.values()],
            "text": [f'{i}' for i in items.keys()],
            "color": [
                clrs[next((k for k, l in status.items() if i in l), "ok")]
                for i in items.keys()
            ],
            "ttips": [ttips[i] for i in items.keys()]
        }
        return dict(data=data)
コード例 #3
0
ファイル: _plot.py プロジェクト: depixusgenome/trackanalysis
    def _data(self, items, nans) -> Dict[str, np.ndarray]:
        if items is None or len(items) == 0 or not any(
                len(i) for _, i in items):
            return {i: [] for i in ("t", "z", "cycle", "color", 'status')}

        dsampl = self._ctrl.theme.get('cleaning.downsampling', 'value', 0)
        order = self._model.cleaning.sorted(self._theme.order)
        if dsampl > 1:
            size = (max(len(i) for _, i in items) // dsampl + 1) * dsampl + 1
        else:
            size = max(len(i) for _, i in items) + 1
        val = np.full((len(items), size), np.NaN, dtype='f4')
        for (_, i), j in items:
            val[order[i], :len(j)] = j

        res = dict(t=repeat(range(val.shape[1]), val.shape[0], 0),
                   z=val.ravel(),
                   cycle=repeat([i[-1] for i, _ in items], val.shape[1], 1),
                   color=self.__color(order, nans, val,
                                      tohex(self._theme.colors)),
                   status=self.__color(order, nans, val, dict(good='',
                                                              **NAMES)))
        assert all(len(i) == val.size for i in res.values())

        if dsampl > 1:
            inds = np.random.randint(0, dsampl,
                                     (val.shape[0], (size - 1) // dsampl + 1))
            inds += (np.arange(inds.shape[1]) * dsampl).T
            inds[:, -1:] = size - 1
            inds += (np.arange(inds.shape[0]) * size)[None].T
            inds = inds.ravel()
            res = {i: j[inds] for i, j in res.items()}
        return res
コード例 #4
0
ファイル: _plot.py プロジェクト: depixusgenome/trackanalysis
 def __hpincolors(self, beads, items, fitpeaks):
     colors = tohex(themed(self, self._theme.pkcolors))
     arr    = np.array([colors['missing']]*len(beads)*len(fitpeaks))
     for ibead, cache in items.items():
         izero = np.searchsorted(beads, ibead)*len(fitpeaks)
         found = cache[1]['id'][np.isfinite(cache[1]['id'])].astype('i4')
         arr[np.searchsorted(fitpeaks,found)+izero] = colors['found']
     return arr
コード例 #5
0
    def _compute_theodata(self, expdata: pd.DataFrame) -> pd.DataFrame:
        if (expdata.shape[0] == 0
                or all(expdata[i].tolist() == self._defaultdata[i]
                       for i in ('x', 'baseposition'))):
            return pd.DataFrame(
                {i: j[:0]
                 for i, j in self._theodata.data.items()})

        hpin: Dict[Tuple[str, int], np.ndarray] = {}
        ids: Set[int] = set(expdata.trackid.unique())
        for proc in self._procs.values():
            iproc = id(proc.model[0])
            if iproc in ids:
                for task in proc.model:
                    hpin.update({(i, iproc): j.peaks
                                 for i, j in getattr(task, 'fit', {}).items()})

        colors = tohex(self._model.theme.colors)
        cols = ['hairpin', 'trackid', 'bead', 'closest']
        ind = expdata.groupby(cols[:-1]).cost.first().index
        bindings = pd.Series([hpin[i[:2]] for i in ind], index=ind, name='var')
        data = (bindings.apply(pd.Series).merge(
            bindings.to_frame().drop(columns=['var']),
            right_index=True,
            left_index=True).reset_index().melt(
                id_vars=cols[:-1], value_name=cols[-1]).drop(
                    columns=['variable']).dropna().assign(
                        status='falseneg', color=colors['falseneg']))

        data.set_index(cols, inplace=True)
        ind = expdata[expdata.status == 'truepos'].groupby(
            cols).x.first().index
        data.loc[ind, 'status'] = 'truepos'
        data.loc[ind, 'color'] = colors['truepos']

        data.reset_index(level=3, inplace=True)
        data = data.join(
            expdata.groupby(cols[:-1]).agg({
                'hairpin': 'first',
                'x': 'first'
            }))

        data.rename(columns={'closest': 'bindingposition'}, inplace=True)

        cnf = copy(self._model.display)
        cnf.ranges = dict(cnf.ranges)
        for i in ('baseposition', 'closest'):
            if cnf.ranges.get(('peaks', i), Slice()) != Slice():
                cnf.ranges[('bindingposition', )] = cnf.ranges.pop(
                    ('peaks', i))
        return cnf.filter(data)
コード例 #6
0
 def _createpeaks(self, itms, out):
     peaks, allpks, factor = self._model.consensuspeaks(itms)
     colors = [
         tohex(themed(self._model.themename, self._theme.pkcolors)[i])
         for i in ('found', 'missing')
     ]
     if itms is not None:
         itms.histogram /= factor
     peaks['color'] = np.where(np.isfinite(peaks['id']), *colors[:2])
     allpks['color'] = np.where(np.isfinite(allpks['id']), *colors[:2])
     out['peaks'] = peaks
     out['events'] = allpks
     out['events']['rate'] = out['events']['count']
     return True
コード例 #7
0
ファイル: _plot.py プロジェクト: depixusgenome/trackanalysis
    def __rawdata(self, track, cycles,
                  zmag) -> Iterator[Dict[str, np.ndarray]]:
        yield {}
        yield {}

        conc = lambda x: np.concatenate(list(x))

        def _get2(vals):
            out = conc(([np.NaN] if j else i) for i in vals for j in (0, 1))
            return popclip(out, *self._theme.clip)

        colors = np.array(tohex(self._theme.phases))
        phase = conc([colors[0]] if j else colors[1:][i]
                     for i in (track.secondaries.phasecycles.withphases(
                         self._theme.phaserange).values()) for j in (0, 1))
        yield dict(z=_get2(cycles), zmag=_get2(zmag), phase=phase)
コード例 #8
0
def createpeaks(mdl, themecolors, vals) -> Dict[str, np.ndarray]:
    "create the peaks ColumnDataSource"
    colors = [
        tohex(themed(mdl.themename, themecolors)[i])
        for i in ('found', 'missing', 'reference')
    ]

    peaks = dict(mdl.peaks)
    peaks['color'] = [colors[0]] * len(peaks.get('id', ()))
    if vals is not None and mdl.identification.task is not None and len(
            mdl.distances):
        for key in mdl.sequences(...):
            peaks[key + 'color'] = np.where(np.isfinite(peaks[key + 'id']),
                                            *colors[:2])
        if mdl.sequencekey + 'color' in peaks:
            peaks['color'] = peaks[mdl.sequencekey + 'color']
    elif mdl.fittoreference.referencepeaks is not None:
        peaks['color'] = np.where(np.isfinite(peaks['id']), colors[2],
                                  colors[0])
    return peaks
コード例 #9
0
    def __compute_expdata(self) -> Tuple[pd.DataFrame, bool]:
        lst = [
            i for i in self._compute_expdata(self.__iter_cache()) if i.shape[0]
        ]
        if not lst:
            return pd.DataFrame(self._defaultdata), True

        colors = tohex(self._model.theme.colors)
        order = self._model.theme.order
        frame = (pd.concat(lst, sort=False, ignore_index=True).assign(
            color=lambda itm: itm.status.apply(colors.get),
            order=lambda itm: itm.status.apply(order.get)))

        frame.sort_values([*self._beadorder(), "order"],
                          ascending=True,
                          inplace=True)
        frame.drop(columns=['order'], inplace=True)

        frame = frame.assign(
            **{i: np.NaN
               for i in set(self._defaultdata) - set(frame.columns)})

        return frame, False
コード例 #10
0
 def __colors(self, name):
     return tohex(themed(self, getattr(self._theme, name).color)
                  if hasattr(self._theme, name) else
                  themed(self, self._theme.pkcolors)[name])