Beispiel #1
0
    def mutsummary(self):
        "View selection coefficient distributions and mutation type counts"

        #calculate number of neutral mutations
        neutral = 0
        for mut in self.mts.mutations():
            if mut.derived_state == '1':
                neutral += 1

        #record fitness coefficients
        coeffs = []
        for mut in self.mts.mutations():
            mut_list = mut.metadata["mutation_list"]
            for i in mut_list:
                coeffs.append(i["selection_coeff"])

        self.coeffs = coeffs

        #altair plot of mutation distrbutions
        mean = sum(coeffs) / len(coeffs)
        dist = np.histogram(coeffs, 50)
        source = pd.DataFrame(
            {
                'counts': dist[0],
                'values': dist[1][:-1],
                'mean': mean
            },
            columns=['values', 'counts', 'mean'])
        base = alt.Chart(source)

        histo = base.mark_bar(
            opacity=0.5, color=alt.ColorName("cornflowerblue")).encode(
                alt.X('values:Q', axis=alt.Axis(title='Fitness Effect')),
                alt.Y('counts:Q'),
                color=alt.condition(
                    alt.datum.values > 0,
                    alt.value("lightseagreen"),  # The positive color
                    alt.value("indianred")  # The negative color
                ),
                tooltip=[
                    alt.Tooltip('values', title='Fitness Effect'),
                ])
        mean = base.mark_rule(color=alt.ColorName("goldenrod"),
                              opacity=0.4).encode(
                                  x='mean:Q',
                                  size=alt.value(3),
                                  tooltip=[
                                      alt.Tooltip('mean(values)',
                                                  title='Mean Fitness Effect'),
                                  ])

        print("Note: this plot does not contain neutral mutations overlaid "
              "with `msprime`.")
        IPython.display.display_html(histo + mean)
        print(f"Total mutations: {self.mts.num_mutations}\n"
              f"Neutral mutations: {neutral}\n"
              f"Non-neutral mutations: {self.mts.num_mutations - neutral}\n")
Beispiel #2
0
    def zoomplot(self):
        "interactive altair plot - but needs to be opened in vega editor"
        chrom = Chromosome(self.genome)
        chrom.altair()
        ichrom = chrom.ichrom

        brush = alt.selection_interval(encodings=['x'],
                                       mark=alt.BrushConfig(fill='red',
                                                            fillOpacity=0.700))

        fadedchrom = ichrom.mark_rect(opacity=0.4)

        mut_pos = pd.DataFrame({'x': self.positions})
        mut_positions = alt.Chart(mut_pos).mark_rule(
            color=alt.ColorName("mediumblue")).encode(
                x='x:Q',
                size=alt.value(1),
                tooltip=[
                    alt.Tooltip('x', title='Position'),
                ])

        layered = alt.layer(fadedchrom, mut_positions)

        zoomtest = alt.vconcat(
            layered.encode(
                alt.X('x1:Q', title=None,
                      scale=alt.Scale(domain=brush))).properties(height=80),
            layered.add_selection(brush).properties(height=30))

        print("Note: this plot must be opened in the Vega editor for "
              "interactive features to work")
        IPython.display.display_html(zoomtest)
Beispiel #3
0
    def plotmuts(self, chromosome=None):
        """
        Plots the mutations over the chromosome as interactive altair 
        plot - but needs to be opened in vega editor (??)
        """

        if self.chromosome == None:
            if chromosome is not None:
                self.chromosome = chromosome
            else:
                logger.warning(
                    "PostSim object was not initialised with"
                    "a chromosome object - please provide one for plot"
                    "function.")
        else:
            self.chromosome.inspect()
            ichrom = self.chromosome.ichrom

            alt.data_transformers.disable_max_rows()
            brush = alt.selection_interval(encodings=['x'],
                                           mark=alt.BrushConfig(
                                               fill='red', fillOpacity=0.700))

            fadedchrom = ichrom.mark_rect(opacity=0.4)

            if len(self.edge_ids) > 1:
                mut_pos = pd.DataFrame({
                    'x': self.positions,
                    'population': str("pop" + self.popids)
                })

                mut_positions = alt.Chart(mut_pos).mark_rule().encode(
                    color=alt.Color('population',
                                    scale=alt.Scale(
                                        domain=self.edge_ids,
                                        range=["mediumblue", "crimson"])),
                    x='x:Q',
                    size=alt.value(1),
                    tooltip=[
                        alt.Tooltip('x', title='Position'),
                    ])
            else:
                mut_pos = pd.DataFrame({'x': self.positions})
                self.mut_pos = mut_pos
                mut_positions = alt.Chart(mut_pos).mark_rule(
                    color=alt.ColorName("mediumblue")).encode(
                        x='x:Q',
                        size=alt.value(1),
                        tooltip=[
                            alt.Tooltip('x', title='Position'),
                        ])

            layered = alt.layer(fadedchrom, mut_positions)

            zoomtest = alt.vconcat(
                layered.encode(
                    alt.X(
                        'x1:Q', title=None,
                        scale=alt.Scale(domain=brush))).properties(height=80),
                layered.add_selection(brush).properties(height=30))

            print("Note: this plot must be opened in the Vega editor for "
                  "interactive features to work")
            IPython.display.display_html(zoomtest)

            self.plot = zoomtest
Beispiel #4
0
    def summary(self):
        "View selection coefficient distributions and mutation type counts"
        #calculate number of neutral mutations
        neutral = 0
        for mut in self.tscoal.mutations():
            if mut.derived_state == '1':
                neutral += 1

        #record fitness coefficients
        coeffs = []
        for mut in self.tscoal.mutations():
            mut_list = mut.metadata["mutation_list"]
            for i in mut_list:
                coeffs.append(i["selection_coeff"])

        #altair plot of mutation distrbutions
        mean = sum(coeffs) / len(coeffs)
        dist = np.histogram(coeffs, 50)
        source = pd.DataFrame(
            {
                'counts': dist[0],
                'values': dist[1][:-1],
                'mean': mean
            },
            columns=['values', 'counts', 'mean'])
        base = alt.Chart(source)

        histo = base.mark_bar(
            opacity=0.5, color=alt.ColorName("cornflowerblue")).encode(
                alt.X('values:Q', axis=alt.Axis(title='Fitness Effect')),
                alt.Y('counts:Q'),
                color=alt.condition(
                    alt.datum.values > 0,
                    alt.value("lightseagreen"),  # The positive color
                    alt.value("indianred")  # The negative color
                ),
                tooltip=[
                    alt.Tooltip('values', title='Fitness Effect'),
                ])
        mean = base.mark_rule(color=alt.ColorName("goldenrod"),
                              opacity=0.4).encode(
                                  x='mean:Q',
                                  size=alt.value(3),
                                  tooltip=[
                                      alt.Tooltip('mean(values)',
                                                  title='Mean Fitness Effect'),
                                  ])

        print("Note: this plot does not contain neutral mutations overlaid "
              "with `msprime`.")
        IPython.display.display_html(histo + mean)
        print(
            f"Total mutations: {self.tscoal.num_mutations}\n"
            f"Neutral mutations: {neutral}\n"
            f"Non-neutral mutations: {self.tscoal.num_mutations - neutral}\n")

        #static toyplot
        print("Mutation positions along chromosome:")
        chrom = Chromosome(genome=self.genome)
        chrom.toyplot()
        self.rectangles = chrom.rectangles

        canvas = toyplot.Canvas(width=2500, height=200)
        axes = canvas.cartesian()
        axes.show = False

        #draw the rectangles
        for index, row in self.rectangles.iterrows():
            axes.rectangle(
                row['x1'],
                row['x2'],
                row['y1'],
                row['y2'],
                color=row['color'],
                style={"opacity": 0.6},
            )
        #draw the positions
        lines = axes.vlines(self.positions,
                            style={
                                "stroke": "blue",
                                "stroke-width": 2
                            })