Ejemplo n.º 1
0
 def on_init(self):
     pygame.init()
     pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),
                             pygame.DOUBLEBUF)
     pygame.display.set_caption('Mandala Magic')
     self.window = Window(pygame.display.get_surface(), pygame.time.Clock())
     self._running = True
Ejemplo n.º 2
0
class Driver:
    def __init__(self):
        self._running = True
        self.window = None
        self.on_init()

    def on_init(self):
        pygame.init()
        pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),
                                pygame.DOUBLEBUF)
        pygame.display.set_caption('Mandala Magic')
        self.window = Window(pygame.display.get_surface(), pygame.time.Clock())
        self._running = True

    def on_event(self, event):
        if event.type == pygame.QUIT:
            self._running = False

    def on_loop(self):
        pass

    def on_render(self):
        self.window.draw()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        while self._running:
            for event in pygame.event.get():
                self.on_event(event)
            self.on_loop()
            self.on_render()
        self.on_cleanup()
Ejemplo n.º 3
0
class Driver:
    def __init__(self, screen, clock):
        self.window = Window(screen, clock)
        self.stream = Stream

    def run(self):
        pa = PyAudio()

        self.stream = pa.open(format=paFloat32,
                              channels=CHANNELS,
                              rate=SAMPLE_RATE,
                              output=False,
                              input=True,
                              stream_callback=self.callback,
                              input_device_index=INPUT_DEVICE_INDEX,
                              frames_per_buffer=CHUNK)

        self.stream.start_stream()

        pyquit = False
        while self.stream.is_active() and not pyquit:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pyquit = True
            sleep(0.76)  # 24 fps

        self.stream.stop_stream()
        self.stream.close()
        pa.terminate()
        pygame.quit()

    def callback(self, in_data, frame_count, time_info, flag):
        """
        :param in_data: audio data from input source
        :param frame_count: 1024
        :param time_info: {'input_buffer_adc_time': ..., 'current_time': ..., 'output_buffer_dac_time': ...}
        :param flag: 0 or 1
        """
        y = np.fromstring(in_data, dtype=np.float32)
        with np.errstate(all='ignore'):
            spectrum = np.nan_to_num(np.log(y))
        self.window.draw(spectrum)

        return in_data, paContinue
Ejemplo n.º 4
0
def main():
    args = parse_args()

    config = SafeConfigParser()
    config.read([args.tracks_file, args.config_file])

    if config.has_option("MAIN", "ASSEMBLY"):
        assembly = config.get("MAIN", "ASSEMBLY")
        gdb = genome.db.GenomeDB(assembly=assembly)
    else:
        gdb = genome.db.GenomeDB()

    sys.stderr.write("using assembly %s\n" % gdb.assembly)

    r = robjects.r

    chrom_dict = gdb.get_chromosome_dict()

    if config.getboolean("MAIN", "DRAW_GENES"):
        tr_dict, gene_dict = get_genes(config, chrom_dict)
    else:
        tr_dict = {}
        gene_dict = {}

    regions = get_regions(config, gene_dict, chrom_dict)
    track_types = get_track_types()

    output_prefix = config.get("MAIN", "OUTPUT_PREFIX")
    output_dir = config.get("MAIN", "OUTPUT_DIR")
    single_file = config.getboolean("MAIN", "SINGLE_FILE")
    width = config.getfloat("MAIN", "WINDOW_WIDTH")
    output_format = config.get("MAIN", "OUTPUT_FORMAT").lower()

    if output_dir:
        if not output_dir.endswith("/"):
            output_dir = output_dir + "/"
        output_prefix = "%s%s" % (output_dir, output_prefix)

    if single_file:
        # get output file parameters
        height = config.getfloat("MAIN", "WINDOW_HEIGHT")
        if height < 5.0:
            # make minimum height 5
            height = 5.0

        if output_format == "pdf":
            filename = "%s.pdf" % output_prefix
            grdevices.pdf(file=filename, width=width, height=height)
        elif output_format == "png":
            filename = "%s.png" % output_prefix
            grdevices.png(file=filename, width=width, height=height)
        else:
            raise ValueError("unknown output format %s" % output_format)

        sys.stderr.write("writing output to single file '%s'\n" % filename)

    plot_num = 0
    for i in range(len(regions)):
        region = regions[i]
        plot_num += 1
        sys.stderr.write("DRAWING REGION %d (%s)\n" % (plot_num, str(region)))

        # create window for this region
        draw_grid = config.getboolean("MAIN", "DRAW_GRID")
        if config.has_option("MAIN", "DRAW_MIDLINE"):
            draw_midline = config.getboolean("MAIN", "DRAW_MIDLINE")
        else:
            draw_midline = False

        # draw some vertical lines on this plot?
        if config.has_option("MAIN", "DRAW_VERTLINES"):
            vert_lines = [
                float(x)
                for x in config.get("MAIN", "DRAW_VERTLINES").split(",")
            ]
            vert_lines_col = ["black"] * len(vert_lines)
        else:
            vert_lines = []
            vert_lines_col = []

        # region attributes can also be used to specify locations of
        # vertical lines
        if config.has_option("MAIN", "VERTLINES_ATTRIBUTES"):
            attr_names = config.get("MAIN", "VERTLINES_ATTRIBUTES").split(",")

            sys.stderr.write("drawing vertical lines corresponding to "
                             "region attrs %s\n" % ",".join(attr_names))

            for a in attr_names:
                if hasattr(region, a):
                    pos = int(getattr(region, a))
                    vert_lines.append(pos)
                else:
                    sys.stderr.write("region is missing attribute %s\n" % a)

            # colors can be specified for these lines
            if config.has_option("MAIN", "VERTLINES_COLORS"):
                cols = config.get("MAIN", "VERTLINES_COLORS").split(",")
                vert_lines_col.extend(cols)

        if len(vert_lines_col) < len(vert_lines):
            # set extra lines to color black
            diff = len(vert_lines) - len(vert_lines_col)
            vert_lines_col.extend(["black"] * diff)

        # sys.stderr.write("vert_lines: %s\n" % repr(vert_lines))
        # sys.stderr.write("vert_lines_col: %s\n" % repr(vert_lines_col))
        margin = config.getfloat("MAIN", "WINDOW_MARGIN")
        cex = config.getfloat("MAIN", "CEX")
        window = Window(region,
                        draw_grid=draw_grid,
                        draw_midline=draw_midline,
                        vert_lines=vert_lines,
                        vert_lines_col=vert_lines_col,
                        margin=margin,
                        cex=cex)

        # add gene tracks to window
        for genes_type in gene_dict.keys():
            sys.stderr.write("  adding genes track %s\n" % genes_type)
            options = dict(config.items(genes_type))
            track_class = track_types[options['type']]
            genes_track = track_class(tr_dict[genes_type], region, options)
            window.add_track(genes_track)

        # add other tracks to window
        track_names = config.get("MAIN", "TRACKS").split(",")
        for track_name in track_names:
            if track_name.strip() == "":
                continue
            sys.stderr.write("  adding track %s\n" % track_name)
            section_name = "TRACK_" + track_name
            if not config.has_section(section_name):
                sys.stderr.write("WARNING: no config section '%s' for "
                                 "track '%s'\n" % (section_name, track_name))
                continue

            options = dict(config.items(section_name))
            # add genome db to the options, so that it can
            # be optionally used by tracks
            options['gdb'] = gdb

            if 'type' not in options:
                sys.stderr.write("WARNING: track %s does not define "
                                 "TYPE in configuration file\n" % track_name)
                continue

            track_type = options['type']

            if track_type not in track_types:
                sys.stderr.write(
                    "WARNING: don't how to create "
                    "track %s with type %s.\n"
                    "         Known types are %s\n" %
                    (track_name, track_type, ", ".join(track_types.keys())))
                continue

            try:
                track_class = track_types[track_type]
                track = track_class(region, options)
                window.add_track(track)
            except TypeError as err:
                sys.stderr.write(("-" * 60) + "\n")
                sys.stderr.write("WARNING: could not init track %s of "
                                 "type %s:\n%s\n" %
                                 (track_name, track_type, str(err)))
                traceback.print_exc()
                sys.stderr.write(("-" * 60) + "\n")
            except ValueError as err:
                sys.stderr.write(("-" * 60) + "\n")
                sys.stderr.write("WARNING: could not open track %s of "
                                 "type %s:\n%s\n" %
                                 (track_name, options['type'], str(err)))
                traceback.print_exc()
                sys.stderr.write(("-" * 60) + "\n")

        if single_file:
            # each region is a separate page of a single PDF
            window.draw(r)
        else:
            # make a separate PDF for each region
            # get output file parameters
            height = config.getfloat("MAIN", "WINDOW_HEIGHT")
            if height <= 0.0:
                height = window.get_height() * 0.5
            if height < 5.0:
                # make minimum height 5 inches
                height = 5.0

            if output_format == "pdf":
                filename = "%s%d.pdf" % (output_prefix, plot_num)
                grdevices.pdf(file=filename, width=width, height=height)

                # turn off clipping
                r.par(xpd=True)

            elif output_format == "png":
                filename = "%s%d.png" % (output_prefix, plot_num)
                grdevices.png(file=filename, width=width, height=height)
            else:
                raise ValueError("unknown output format %s" % output_format)

            # render window
            window.draw(r)
            grdevices.dev_off()

    if single_file:
        grdevices.dev_off()
Ejemplo n.º 5
0
def main():
    if len(sys.argv) != 2:
        sys.stderr.write("usage: %s <config_file>\n" % sys.argv[0])
        exit(2)
    
    config = SafeConfigParser()
    config.read(['conf/tracks.conf', sys.argv[1]])

    if config.has_option("MAIN", "ASSEMBLY"):
        assembly = config.get("MAIN", "ASSEMBLY")
        gdb = genome.db.GenomeDB(assembly=assembly)
    else:
        gdb = genome.db.GenomeDB()

    sys.stderr.write("using assembly %s\n" % gdb.assembly)

    r = robjects.r
    chrom_dict = gdb.get_chromosome_dict()

    if config.getboolean("MAIN", "DRAW_GENES"):
        tr_dict, gene_dict = get_genes(config, chrom_dict)
    else:
        tr_dict = {}
        gene_dict = {}
    
    regions = get_regions(config, gene_dict, chrom_dict)
    track_types = get_track_types()
    
    output_prefix = config.get("MAIN", "OUTPUT_PREFIX")
    output_dir = config.get("MAIN", "OUTPUT_DIR")
    single_file = config.getboolean("MAIN", "SINGLE_FILE")
    width = config.getfloat("MAIN", "WINDOW_WIDTH")
    output_format = config.get("MAIN", "OUTPUT_FORMAT").lower()

    if output_dir:
        if not output_dir.endswith("/"):
            output_dir = output_dir + "/"
        output_prefix = "%s%s" % (output_dir, output_prefix)

    if single_file:
        # get output file parameters
        height = config.getfloat("MAIN", "WINDOW_HEIGHT")
        if height < 5.0:
            # make minimum height 5
            height = 5.0

        if output_format == "pdf":
            filename = "%s.pdf" % output_prefix
            grdevices.pdf(file=filename, width=width, height=height)
        elif output_format == "png":
            filename = "%s.png" % output_prefix
            grdevices.png(file=filename, width=width, height=height)
        else:
            raise ValueError("unknown output format %s" % output_format)

        sys.stderr.write("writing output to single file '%s'\n" % filename)


    plot_num = 0
    for i in range(len(regions)):
        region = regions[i]
        plot_num += 1
        sys.stderr.write("DRAWING REGION %d (%s)\n" %
                         (plot_num, str(region)))

        # create window for this region
        draw_grid = config.getboolean("MAIN", "DRAW_GRID")
        if config.has_option("MAIN", "DRAW_MIDLINE"):
            draw_midline = config.getboolean("MAIN", "DRAW_MIDLINE")
        else:
            draw_midline = False

        # draw some vertical lines on this plot?
        if config.has_option("MAIN", "DRAW_VERTLINES"):
            vert_lines = [float(x) for x in config.get("MAIN","DRAW_VERTLINES").split(",")]
        else:
            vert_lines = []
        
        margin = config.getfloat("MAIN", "WINDOW_MARGIN")
        cex = config.getfloat("MAIN", "CEX")
        window = Window(region, draw_grid=draw_grid,
                        draw_midline=draw_midline,
                        vert_lines=vert_lines,
                        margin=margin, cex=cex)

        # add gene tracks to window
        for genes_type in gene_dict.keys():
            sys.stderr.write("  adding genes track %s\n" % genes_type)
            options = dict(config.items(genes_type))
            track_class = track_types[options['type']]
            genes_track = track_class(tr_dict[genes_type], region, options)
            window.add_track(genes_track)

        # add other tracks to window
        track_names = config.get("MAIN", "TRACKS").split(",")
        for track_name in track_names:
            if track_name.strip() == "":
                continue
            sys.stderr.write("  adding track %s\n" % track_name)

            section_name = "TRACK_" + track_name
            if not config.has_section(section_name):
                sys.stderr.write("WARNING: no config section '%s' for "
                                 "track '%s'\n" % (section_name, track_name))
                continue

            options = dict(config.items(section_name))
            # add genome db to the options, so that it can
            # be optionally used by tracks
            options['gdb'] = gdb

            if 'type' not in options:
                sys.stderr.write("WARNING: track %s does not define "
                                 "TYPE in configuration file\n" % track_name)
                continue

            track_type = options['type']

            if track_type not in track_types:
                sys.stderr.write("WARNING: don't how to create "
                                 "track %s with type %s.\n"
                                 "         Known types are %s\n"
                                 % (track_name, track_type,
                                    ", ".join(track_types.keys())))
                continue
            
            try:
                track_class = track_types[track_type]
                track = track_class(region, options)
                window.add_track(track)
            except TypeError as err:
                sys.stderr.write("WARNING: could not init track %s of "
                                 "type %s:\n%s\n" %
                                 (track_name, track_type, str(err)))
            except ValueError as err:
                sys.stderr.write("WARNING: could not open track %s of "
                                 "type %s:\n%s\n" %
                                 (track_name, options['type'], str(err)))

        if single_file:
            # each region is a separate page of a single PDF
            window.draw(r)
        else:
            # make a separate PDF for each region            
            # get output file parameters
            height = config.getfloat("MAIN", "WINDOW_HEIGHT")
            if height <= 0.0:
                height = window.get_height() * 0.5
            if height < 5.0:
                # make minimum height 5 inches
                height = 5.0

            if output_format == "pdf":
                filename = "%s%d.pdf" % (output_prefix, plot_num)
                grdevices.pdf(file=filename, width=width, height=height)
            elif output_format == "png":
                filename = "%s%d.png" % (output_prefix, plot_num)
                grdevices.png(file=filename, width=width, height=height)
            else:
                raise ValueError("unknown output format %s" % output_format)

            # render window
            window.draw(r)
            grdevices.dev_off()


    if single_file:
        grdevices.dev_off()
Ejemplo n.º 6
0
 def __init__(self, screen, clock):
     self.window = Window(screen, clock)
     self.stream = Stream
Ejemplo n.º 7
0
def main():
    args = parse_args()
        
    config = ConfigParser()
    config.read([args.tracks_file, args.config_file])

    r = robjects.r
    
    chrom_dict = genome.chrom.parse_chromosomes_dict(config.get("MAIN",
                                                                "CHROM_INFO"))

    gene_types = []
    if config.getboolean("MAIN", "DRAW_GENES"):
        genes_str = config.get("MAIN", "GENES")
        gene_types = genes_str.split(",")
        gene_dict = get_genes(config, chrom_dict)
    else:
        gene_dict = {}
    
    regions = region.get_regions(config, gene_dict, chrom_dict)
    track_types = get_track_types()
    
    output_prefix = config.get("MAIN", "OUTPUT_PREFIX")
    output_dir = config.get("MAIN", "OUTPUT_DIR")
    single_file = config.getboolean("MAIN", "SINGLE_FILE")
    width = config.getfloat("MAIN", "WINDOW_WIDTH")
    output_format = config.get("MAIN", "OUTPUT_FORMAT").lower()

    if output_dir:
        if not output_dir.endswith("/"):
            output_dir = output_dir + "/"
        output_prefix = "%s%s" % (output_dir, output_prefix)

    if single_file:
        # get output file parameters
        height = config.getfloat("MAIN", "WINDOW_HEIGHT")
        if height < 5.0:
            # make minimum height 5
            height = 5.0

        if output_format == "pdf":
            filename = "%s.pdf" % output_prefix
            grdevices.pdf(file=filename, width=width, height=height)
        elif output_format == "png":
            filename = "%s.png" % output_prefix
            grdevices.png(file=filename, width=width, height=height)
        else:
            raise ValueError("unknown output format %s" % output_format)

        sys.stderr.write("writing output to single file '%s'\n" % filename)

        
    plot_num = 0
    for i in range(len(regions)):
        reg = regions[i]
        plot_num += 1
        sys.stderr.write("DRAWING REGION %d (%s)\n" %
                         (plot_num, str(reg)))

        # create window for this region
        draw_grid = config.getboolean("MAIN", "DRAW_GRID")
        if config.has_option("MAIN", "DRAW_MIDLINE"):
            draw_midline = config.getboolean("MAIN", "DRAW_MIDLINE")
        else:
            draw_midline = False

        # draw some vertical lines on this plot?
        if config.has_option("MAIN", "DRAW_VERTLINES"):
            vert_lines = [float(x) for x in config.get("MAIN","DRAW_VERTLINES").split(",")]
            vert_lines_col = ["black"] * len(vert_lines)
        else:
            vert_lines = []
            vert_lines_col = []

        # region attributes can also be used to specify locations of
        # vertical lines
        if config.has_option("MAIN", "VERTLINES_ATTRIBUTES"):
            attr_names = config.get("MAIN", "VERTLINES_ATTRIBUTES").split(",")

            sys.stderr.write("drawing vertical lines corresponding to "
                             "region attrs %s\n" %",".join(attr_names))
            
            for a in attr_names:
                if hasattr(reg, a):
                    pos = int(getattr(reg, a))
                    vert_lines.append(pos)
                else:
                    sys.stderr.write("region is missing attribute %s\n" % a)
                
            # colors can be specified for these lines
            if config.has_option("MAIN", "VERTLINES_COLORS"):
                cols = config.get("MAIN", "VERTLINES_COLORS").split(",")
                vert_lines_col.extend(cols)

        if len(vert_lines_col) < len(vert_lines):
            # set extra lines to color black
            diff = len(vert_lines) - len(vert_lines_col)
            vert_lines_col.extend(["black"] * diff)

        # sys.stderr.write("vert_lines: %s\n" % repr(vert_lines))
        # sys.stderr.write("vert_lines_col: %s\n" % repr(vert_lines_col))
        margin = config.getfloat("MAIN", "WINDOW_MARGIN")
        cex = config.getfloat("MAIN", "CEX")
        window = Window(reg, draw_grid=draw_grid,
                        draw_midline=draw_midline,
                        vert_lines=vert_lines,
                        vert_lines_col=vert_lines_col,
                        margin=margin, cex=cex)

        # add gene tracks to window
        for genes_type in gene_types:
            gene_label = "GENE_" + genes_type 
            sys.stderr.write("  adding genes track %s\n" % gene_label)
            options = dict(config.items(gene_label))
            track_class = track_types[options['type']]
            genes_track = track_class(gene_dict[gene_label], reg, options)
            window.add_track(genes_track)

        # add other tracks to window
        track_names = config.get("MAIN", "TRACKS").split(",")
        for track_name in track_names:
            if track_name.strip() == "":
                continue
            sys.stderr.write("  adding track %s\n" % track_name)
            section_name = "TRACK_" + track_name
            if not config.has_section(section_name):
                sys.stderr.write("WARNING: no config section '%s' for "
                                 "track '%s'\n" % (section_name, track_name))
                continue

            options = dict(config.items(section_name))

            if 'type' not in options:
                sys.stderr.write("WARNING: track %s does not define "
                                 "TYPE in configuration file\n" % track_name)
                continue

            track_type = options['type']

            if track_type not in track_types:
                sys.stderr.write("WARNING: don't how to create "
                                 "track %s with type %s.\n"
                                 "         Known types are %s\n"
                                 % (track_name, track_type,
                                    ", ".join(list(track_types.keys()))))
                continue
            
            try:
                track_class = track_types[track_type]
                track = track_class(reg, options)
                window.add_track(track)
            except TypeError as err:
                sys.stderr.write(("-" * 60) + "\n") 
                sys.stderr.write("WARNING: could not init track %s of "
                                 "type %s:\n%s\n" %
                                 (track_name, track_type, str(err)))
                traceback.print_exc()
                sys.stderr.write(("-" * 60) + "\n") 
            except ValueError as err:
                sys.stderr.write(("-" * 60) + "\n") 
                sys.stderr.write("WARNING: could not open track %s of "
                                 "type %s:\n%s\n" %
                                 (track_name, options['type'], str(err)))
                traceback.print_exc()
                sys.stderr.write(("-" * 60) + "\n") 
        
        if single_file:
            # each region is a separate page of a single PDF
            window.draw(r)
        else:
            # make a separate PDF for each region            
            # get output file parameters
            height = config.getfloat("MAIN", "WINDOW_HEIGHT")
            if height <= 0.0:
                height = window.get_height() * 0.5
            if height < 5.0:
                # make minimum height 5 inches
                height = 5.0

            if output_format == "pdf":
                filename = "%s%d.pdf" % (output_prefix, plot_num)
                grdevices.pdf(file=filename, width=width, height=height)
                
                # turn off clipping
                r.par(xpd=True)

            elif output_format == "png":
                filename = "%s%d.png" % (output_prefix, plot_num)
                grdevices.png(file=filename, width=width, height=height)
            else:
                raise ValueError("unknown output format %s" % output_format)
            
            # render window
            window.draw(r)
            grdevices.dev_off()


    if single_file:
        grdevices.dev_off()
Ejemplo n.º 8
0
    output_filename = "%s.%s" % (tr_name, output_format)
    width = 8
    height = 5

    sys.stderr.write("drawing transcript (filename=%s)\n" % output_filename)

    grdevices.pdf(file=output_filename, width=width, height=height)

    region = tr
    options = {
        'color': "#08306B",
        'utr_color': '#DEEBF7',
        'border': 'false',
        'height': 0.1
    }

    window = Window(region, draw_grid=False)

    tr_track = TranscriptTrack(tr, region, options)
    window.add_track(tr_track)

    window.draw(r)

    # top = 0
    # bottom = -1
    # tr_track.set_position(tr.start, tr.end, top, bottom)

    # tr_track.draw_track(r)

    grdevices.dev_off()
Ejemplo n.º 9
0
output_filename = "%s.%s" % (tr_name, output_format)
width=8
height=5


sys.stderr.write("drawing transcript (filename=%s)\n" % output_filename)

grdevices.pdf(file=output_filename, width=width, height=height)

region = tr
options = {'color' : "#08306B",
           'utr_color' : '#DEEBF7', 
           'border' : 'false',
           'height' : 1}

window = Window(region, draw_grid=False)

tr_track = TranscriptTrack(tr, region, options)
window.add_track(tr_track)

window.draw(r)

# top = 0
# bottom = -1
# tr_track.set_position(tr.start, tr.end, top, bottom)

# tr_track.draw_track(r)

grdevices.dev_off()