Example #1
0
    def _pct2rgb(self, src_filename, dst_filename):
        """!Create new dataset with data in dst_filename with bands according to src_filename
        raster color table - modified code from gdal utility pct2rgb

        @return new dataset
        """
        out_bands = 4
        band_number = 1

        # open source file
        src_ds = gdal.Open(src_filename)
        if src_ds is None:
            grass.fatal(_("Unable to open %s " % src_filename))

        src_band = src_ds.GetRasterBand(band_number)

        # Build color table
        lookup = [
            Numeric.arrayrange(256),
            Numeric.arrayrange(256),
            Numeric.arrayrange(256),
            Numeric.ones(256) * 255,
        ]

        ct = src_band.GetRasterColorTable()
        if ct is not None:
            for i in range(min(256, ct.GetCount())):
                entry = ct.GetColorEntry(i)
                for c in range(4):
                    lookup[c][i] = entry[c]

        # create the working file
        gtiff_driver = gdal.GetDriverByName(self.gdal_drv_format)
        tif_ds = gtiff_driver.Create(
            dst_filename, src_ds.RasterXSize, src_ds.RasterYSize, out_bands
        )

        # do the processing one scanline at a time
        for iY in range(src_ds.RasterYSize):
            src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)

            for iBand in range(out_bands):
                band_lookup = lookup[iBand]

                dst_data = Numeric.take(band_lookup, src_data)
                tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)

        return tif_ds
Example #2
0
 def write_level(self, dataset, table_name, zoom_level, overview_level, matrix_width, matrix_height):
     """
     Write one zoom/resolution level into pyramid data table.
     @param dataset: Input dataset.
     @param table_name: Name of table to write pyramid data into.
     @param zoom_level: Zoom/Resolution level to write.
     @param overview_level: Index to overview to use.
     @param matrix_width: Number of tiles in X.
     @param matrix_height: Number of tiles in Y.
     @return: True on success, False on failure.
     """
     in_band_count = dataset.RasterCount
     out_band_count = in_band_count
     src_bands = list()
     expand_palette = False
     for i in range(in_band_count):
         if overview_level == 0:
             src_bands.append(dataset.GetRasterBand(i + 1))
         else:
             src_bands.append(dataset.GetRasterBand(i + 1).GetOverview(overview_level - 1))
     if self.format == 'image/jpeg' and in_band_count == 1 and \
                     src_bands[0].GetRasterColorInterpretation() == GCI_PaletteIndex:
         out_band_count = 3
         expand_palette = True
     if expand_palette:
         color_table = src_bands[0].GetRasterColorTable()
         if color_table is not None:
             color_table_size = max(256, color_table.GetCount())
             lut = [numpy.arrayrange(color_table_size),
                    numpy.arrayrange(color_table_size),
                    numpy.arrayrange(color_table_size),
                    numpy.ones(color_table_size) * 255]
             for i in range(color_table_size):
                 entry = color_table.GetColorEntry(i)
                 for c in range(4):
                     lut[c][i] = entry[c]
     else:
         lut = None
     for tile_row in range(matrix_height):
         for tile_column in range(matrix_width):
             if not self.write_tile(src_bands, out_band_count,
                                    table_name, zoom_level,
                                    tile_row, tile_column, expand_palette, lut):
                 print("Error writing full resolution image tiles to database.")
                 return False
     return True
Example #3
0
    def _pct2rgb(self, src_filename, dst_filename):
        """!Create new dataset with data in dst_filename with bands according to src_filename
        raster color table - modified code from gdal utility pct2rgb

        @return new dataset
        """
        out_bands = 4
        band_number = 1

        # open source file
        src_ds = gdal.Open(src_filename)
        if src_ds is None:
            grass.fatal(_('Unable to open %s ' % src_filename))

        src_band = src_ds.GetRasterBand(band_number)

        # Build color table
        lookup = [Numeric.arrayrange(256),
                  Numeric.arrayrange(256),
                  Numeric.arrayrange(256),
                  Numeric.ones(256) * 255]

        ct = src_band.GetRasterColorTable()
        if ct is not None:
            for i in range(min(256, ct.GetCount())):
                entry = ct.GetColorEntry(i)
                for c in range(4):
                    lookup[c][i] = entry[c]

        # create the working file
        gtiff_driver = gdal.GetDriverByName(self.gdal_drv_format)
        tif_ds = gtiff_driver.Create(dst_filename,
                                     src_ds.RasterXSize, src_ds.RasterYSize, out_bands)

        # do the processing one scanline at a time
        for iY in range(src_ds.RasterYSize):
            src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)

            for iBand in range(out_bands):
                band_lookup = lookup[iBand]

                dst_data = Numeric.take(band_lookup, src_data)
                tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)

        return tif_ds
Example #4
0
def sample_from( display = True ):
    test_x = [ [x] for x in numpy.arrayrange(0,5,.05) ]
    test_y = infpy.gp_sample_from( gp, test_x )

    if display:
        from pylab import figure, plot, show, fill, title
        figure()
        infpy.gp_plot_prediction( gp.X, test_y )
        title('Log likelihood: %f\n%s' % ( gp.log_p_y_given_X, gp.k.params ) )
        show()
def findPeak(image):
        for n in range(image.shape[1]):
                a = numpy.zeros((image.shape[0], 3))
                b = image[:, n]
                a[:, 0] = numpy.arange(image.shape[0])
                a[:, 0] **= 2
                a[:, 1] = numpy.arrayrange(image.shape[0])
                a[:, 2] = numpy.ones(image.shape[0])
                fit = scipy.linalg.lstsq(a, b)
                c = fit[0]
                row = -c[1] / (2.0 * c[0])
Example #6
0
def predict_values( display = True ):
    test_x = [ [x] for x in numpy.arrayrange(0,5,.04) ]
    ( f_star_mean, V_f_star, log_p_y_given_X ) = gp.predict( test_x )

    if display:
        from pylab import figure, plot, show, fill, title
        figure()
        infpy.gp_plot_prediction( test_x, f_star_mean, V_f_star )
        plot(
                [ x[0] for (x, v) in training_points ],
                [ v for (x, v) in training_points ],
                'rs' )
        infpy.gp_title_and_show( gp )
Example #7
0
def demo():
    data = Numeric.arrayrange(w*h)

##    fftdata = FFT.fft(data)
##    fftdata2 = FFT.fft(data2)
##    fftdata3 = (fftdata + fftdata2) / 2.
##    invfftdata = FFT.inverse_fft(fftdata3)
##    data = invfftdata.real
    data = data.astype('l')

    im = Image.new("RGBA", (w, h))
    print len(data.tostring("raw", "RGBX", 0, -1))
    print len(im.tostring("raw", "RGBX", 0, -1))
    im.fromstring(data.tostring("raw", "RGBX", 0, -1),"raw", "RGBX", 0, -1)

    root = Tkinter.Tk()
    image = ImageTk.PhotoImage(im)
    x = Tkinter.Label(root, image=image)
    x.pack()

    root.mainloop()
Example #8
0
def demo():
    data = Numeric.arrayrange(w * h)

    ##    fftdata = FFT.fft(data)
    ##    fftdata2 = FFT.fft(data2)
    ##    fftdata3 = (fftdata + fftdata2) / 2.
    ##    invfftdata = FFT.inverse_fft(fftdata3)
    ##    data = invfftdata.real
    data = data.astype('l')

    im = Image.new("RGBA", (w, h))
    print len(data.tostring("raw", "RGBX", 0, -1))
    print len(im.tostring("raw", "RGBX", 0, -1))
    im.fromstring(data.tostring("raw", "RGBX", 0, -1), "raw", "RGBX", 0, -1)

    root = Tkinter.Tk()
    image = ImageTk.PhotoImage(im)
    x = Tkinter.Label(root, image=image)
    x.pack()

    root.mainloop()
Example #9
0
def hist(v, nbins=10, vmin=None, vmax=None, show=None, p=None):
    global _matlab
    p = _matlab.get_plot(p)

    if vmin is None:
        vmin = float(min(v))
    if vmax is None:
        vmax = float(max(v))
    binwidth = (vmax - vmin) / float(nbins - 1)
    x = numpy.arrayrange(vmin, vmax + binwidth, binwidth)
    y = numpy.zeros(x.shape, int)

    for i in range(len(v)):
        n = int(round((float(v[i]) - vmin) / binwidth, 0))
        try:
            y[n] = y[n] + 1
        except IndexError:
            pass

    xx = numpy.zeros(2 * len(x) + 3)
    yy = numpy.zeros(2 * len(y) + 3)
    xx[0] = x[0]
    yy[0] = 0

    for i in range(0, len(x)):
        xx[1 + 2 * i], xx[1 + 2 * i + 1] = x[i], x[i] + binwidth
        yy[1 + 2 * i], yy[1 + 2 * i + 1] = y[i], y[i]

    xx[1 + 2 * i + 2] = x[i] + binwidth
    yy[1 + 2 * i + 2] = 0
    xx[1 + 2 * i + 3] = x[0]
    yy[1 + 2 * i + 3] = 0

    p.add(biggles.FillBelow(xx, yy), biggles.Curve(xx, yy))
    p.yrange = 0, max(y)

    if show is not None:
        p.show()
    _matlab.LAST = p
    return p
Example #10
0
def hist( v, nbins=10, vmin=None, vmax=None, show=None, p=None ):
	global _matlab
	p = _matlab.get_plot( p )
        
	if vmin is None:
		vmin = float(min(v))
	if vmax is None:
		vmax = float(max(v))
	binwidth = (vmax - vmin) / float(nbins-1)
	x = numpy.arrayrange( vmin, vmax+binwidth, binwidth )
	y = numpy.zeros( x.shape, int )

	for i in range(len(v)):
		n = int(round((float(v[i]) - vmin) / binwidth, 0))
		try:
			y[n] = y[n] + 1
		except IndexError:
			pass

	xx = numpy.zeros( 2*len(x) + 3 )
	yy = numpy.zeros( 2*len(y) + 3 )
	xx[0] = x[0]
	yy[0] = 0

	for i in range(0, len(x)):
		xx[1+2*i],xx[1+2*i+1] = x[i],x[i]+binwidth
		yy[1+2*i],yy[1+2*i+1] = y[i],y[i]

	xx[1+2*i+2] = x[i]+binwidth
	yy[1+2*i+2] = 0;
	xx[1+2*i+3] = x[0];
	yy[1+2*i+3] = 0;

	p.add( biggles.FillBelow(xx, yy), biggles.Curve(xx, yy) )
	p.yrange = 0, max(y)

	if show is not None:
		p.show()
	_matlab.LAST = p
	return p
Example #11
0
# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

ct = src_band.GetRasterColorTable()

ct_size = ct.GetCount()
lookup = [
    Numeric.arrayrange(ct_size),
    Numeric.arrayrange(ct_size),
    Numeric.arrayrange(ct_size),
    Numeric.ones(ct_size) * 255,
]

if ct is not None:
    for i in range(ct_size):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.

if format == "GTiff":
Example #12
0
    sys.exit(1)

src_band = src_ds.GetRasterBand(band_number)

# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

lookup = [ Numeric.arrayrange(256), 
           Numeric.arrayrange(256), 
           Numeric.arrayrange(256), 
           Numeric.ones(256)*255 ]

ct = src_band.GetRasterColorTable()

if ct is not None:
    for i in range(min(256,ct.GetCount())):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.
Example #13
0
def readLiftOver( infile, chromosome,
                  chromosome_size = 250000000,
                  report_step = 1000000 ):
    """read a matrix. There probably is a routine for this in Numpy, which
    I haven't found yet.
    """

    if options.loglevel >= 2:
        print "## started reading mapping information"
        sys.stdout.flush()
        
    map_position   = numpy.zeros( (chromosome_size,), numpy.int) 
    
    ## signed character for chromosme, negative values for negative strands
    map_chromosome = numpy.zeros( (chromosome_size,), numpy.int8 )

    map_id2chromosome = ["",]
    map_chromosome2id = {}
    n = 0
    
    for line in infile:

        n += 1

        if not (n % report_step):
            if options.loglevel >= 2:
                print "# iteration %i" % n
                sys.stdout.flush()
                
        if line[:5] == "chain":
            ( chr_x, size_x, strand_x, first_x, last_x,
              chr_y, size_y, strand_y, first_y, last_y,
              dontknow) = line[:-1].split(" ")[2:]

            if strand_x == "-":
                raise "what shall I do with negative strands?"

            x = int(first_x)
            
            ## revert coordinates for negative strands (it seems that
            ## the mapping file uses reverse coordinates, while liftover
            ## output doesn't)
            ## add 1 to coordinates, because 0 is flag for unmappable.
            if strand_y == "-":
                invert = True
                ## no +1, because already one past current residue (due to open
                ## bracket)
                y = int(size_y) - int(first_y) 
            else:
                invert = False
                y = int(first_y) + 1
            
            if chr_x != chromosome:
                keep = False
            else:
                keep = True
                if options.loglevel >= 3:
                    print "# adding alignment", line[:-1]
                    
            continue
        
        elif line.strip() == "":
            keep = False
            continue
            
        elif keep:
            
            data = map(int, line[:-1].split("\t"))
            
            if len(data) == 3:
                size, increment_x, increment_y = data
            else:
                size, increment_x, increment_y = data[0], 0, 0

            # add position
            if invert:
                map_position[ x:x+size ] = numpy.arrayrange( y, y-size, -1 )
            else:
                map_position[ x:x+size ] = numpy.arrayrange( y, y+size, 1 )

            if chr_y not in map_id2chromosome:
                map_chromosome2id[chr_y] = len(map_id2chromosome)                 
                map_id2chromosome.append( chr_y )
                
            id = map_chromosome2id[chr_y]
            if strand_y == "-": id = -id

            # add chromsome
            map_chromosome[x:x+size] = id

            x += increment_x + size
            if invert:
                y -= increment_y + size
            else:
                y += increment_y + size

            if y < 0:
                raise "illegal mapping: %i -> %i for %s %s:%s-%s(%s) to %s %s: %s-%s(%s)" % ( x, y, 
                                                                                              chr_x, strand_x, first_x, last_x, size_x,
                                                                                              chr_y, strand_y, first_y, last_y, size_y )
            
    return map_position, map_chromosome, map_chromosome2id, map_id2chromosome
Example #14
0
time = 4  # data length in seconds
sample_length = int(time * record.frequency)  # data length in sample units
end_time = start_time + time  # end position in seconds

signals_num = record.nsig  # number of signals in record

# default annotation file has .atr extension
default_ann = record.annotation()

## read all annotations for given range
annotations = default_ann.read(int(start_time * record.frequency),
                               sample_length)

## drawing stuff follows
ylims = (-1.5, 1.5)
t = numpy.arrayrange(start_time, end_time, 1 / record.frequency)
vl = numpy.arange(start_time, end_time, 0.2)
hl = numpy.arange(ylims[0], ylims[1], 0.5)

f = pylab.figure()
f.subplots_adjust(hspace=0.00001)

axes = []
ax = pylab.subplot(signals_num, 1, 1)
pylab.title('ECG record %s' % record.name)

annotation_lines = [ann.time / record.frequency for ann in annotations]


def mark_annotations(ax):
    annotation_font = {
if frmt is None:
    frmt = GetOutputDriverFor(dst_filename)

dst_driver = gdal.GetDriverByName(frmt)
if dst_driver is None:
    print('"%s" driver not registered.' % frmt)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

ct = src_band.GetRasterColorTable()

ct_size = ct.GetCount()
lookup = [
    Numeric.arrayrange(ct_size),
    Numeric.arrayrange(ct_size),
    Numeric.arrayrange(ct_size),
    Numeric.ones(ct_size) * 255
]

if ct is not None:
    for i in range(ct_size):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.

if frmt == 'GTiff':
Example #16
0
    sys.exit(1)

src_band = src_ds.GetRasterBand(band_number)

# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

lookup = [ Numeric.arrayrange(256), 
           Numeric.arrayrange(256), 
           Numeric.arrayrange(256), 
           Numeric.ones(256)*255 ]


ct = src_band.GetRasterColorTable()
print ct
if ct is not None:
    for i in range(min(256,ct.GetCount())):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]


Example #17
0
def doit(src_filename, dst_filename, band_number=1, out_bands=3, frmt=None):
    # Open source file
    src_ds = gdal.Open(src_filename)
    if src_ds is None:
        print('Unable to open %s ' % src_filename)
        return None, 1

    src_band = src_ds.GetRasterBand(band_number)

    # ----------------------------------------------------------------------------
    # Ensure we recognise the driver.

    if frmt is None:
        frmt = GetOutputDriverFor(dst_filename)

    dst_driver = gdal.GetDriverByName(frmt)
    if dst_driver is None:
        print('"%s" driver not registered.' % frmt)
        return None, 1

    # ----------------------------------------------------------------------------
    # Build color table.

    ct = src_band.GetRasterColorTable()

    ct_size = ct.GetCount()
    lookup = [
        Numeric.arrayrange(ct_size),
        Numeric.arrayrange(ct_size),
        Numeric.arrayrange(ct_size),
        Numeric.ones(ct_size) * 255
    ]

    if ct is not None:
        for i in range(ct_size):
            entry = ct.GetColorEntry(i)
            for c in range(4):
                lookup[c][i] = entry[c]

    # ----------------------------------------------------------------------------
    # Create the working file.

    if frmt == 'GTiff':
        tif_filename = dst_filename
    else:
        tif_filename = 'temp.tif'

    gtiff_driver = gdal.GetDriverByName('GTiff')

    tif_ds = gtiff_driver.Create(tif_filename, src_ds.RasterXSize,
                                 src_ds.RasterYSize, out_bands)

    # ----------------------------------------------------------------------------
    # We should copy projection information and so forth at this point.

    tif_ds.SetProjection(src_ds.GetProjection())
    tif_ds.SetGeoTransform(src_ds.GetGeoTransform())
    if src_ds.GetGCPCount() > 0:
        tif_ds.SetGCPs(src_ds.GetGCPs(), src_ds.GetGCPProjection())

    # ----------------------------------------------------------------------------
    # Do the processing one scanline at a time.

    progress(0.0)
    for iY in range(src_ds.RasterYSize):
        src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)

        for iBand in range(out_bands):
            band_lookup = lookup[iBand]

            dst_data = Numeric.take(band_lookup, src_data)
            tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)

        progress((iY + 1.0) / src_ds.RasterYSize)

    # ----------------------------------------------------------------------------
    # Translate intermediate file to output format if desired format is not TIFF.

    if tif_filename == dst_filename:
        dst_ds = tif_ds
    else:
        dst_ds = dst_driver.CreateCopy(dst_filename, tif_ds)
        tif_ds = None
        gtiff_driver.Delete(tif_filename)

    return dst_ds, 0
Example #18
0
    sys.exit(1)

src_band = src_ds.GetRasterBand(band_number)

# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

lookup = [Numeric.arrayrange(256), Numeric.arrayrange(256), Numeric.arrayrange(256), Numeric.ones(256) * 255]

ct = src_band.GetRasterColorTable()

if ct is not None:
    for i in range(min(256, ct.GetCount())):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.

if format == "GTiff":
    tif_filename = dst_filename
else:
Example #19
0
import infpy, numpy, math
from pylab import plot

x = numpy.arrayrange(0.0,5.0,.01)
plot( x, [ math.exp( infpy.LogNormalDistribution( 0.1, 1.0 ).log_pdf( x1 ) ) for x1 in x ] )
plot( x, [ math.exp( infpy.LogNormalDistribution( math.log( 0.03 ), 1.0 ).log_pdf( x1 ) ) for x1 in x ] )
plot( x, [ math.exp( infpy.LogNormalDistribution( 1.0, 1.0 ).log_pdf( x1 ) ) for x1 in x ] )
src_band = src_ds.GetRasterBand(band_number)

# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

lookup = [
    Numeric.arrayrange(256),
    Numeric.arrayrange(256),
    Numeric.arrayrange(256),
    Numeric.ones(256) * 255
]

ct = src_band.GetRasterColorTable()

if ct is not None:
    for i in range(min(256, ct.GetCount())):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.
# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

ct = src_band.GetRasterColorTable()

ct_size = ct.GetCount()
lookup = [Numeric.arrayrange(ct_size),
          Numeric.arrayrange(ct_size),
          Numeric.arrayrange(ct_size),
          Numeric.ones(ct_size) * 255]

if ct is not None:
    for i in range(ct_size):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.

if format == 'GTiff':
    tif_filename = dst_filename
Example #22
0
def readLiftOver(infile,
                 chromosome,
                 chromosome_size=250000000,
                 report_step=1000000):
    """read a matrix. There probably is a routine for this in Numpy, which
    I haven't found yet.
    """

    if options.loglevel >= 2:
        print "## started reading mapping information"
        sys.stdout.flush()

    map_position = numpy.zeros((chromosome_size, ), numpy.int)

    # signed character for chromosme, negative values for negative strands
    map_chromosome = numpy.zeros((chromosome_size, ), numpy.int8)

    map_id2chromosome = [
        "",
    ]
    map_chromosome2id = {}
    n = 0

    for line in infile:

        n += 1

        if not (n % report_step):
            if options.loglevel >= 2:
                print "# iteration %i" % n
                sys.stdout.flush()

        if line[:5] == "chain":
            (chr_x, size_x, strand_x, first_x, last_x, chr_y, size_y, strand_y,
             first_y, last_y, dontknow) = line[:-1].split(" ")[2:]

            if strand_x == "-":
                raise "what shall I do with negative strands?"

            x = int(first_x)

            # revert coordinates for negative strands (it seems that
            # the mapping file uses reverse coordinates, while liftover
            # output doesn't)
            # add 1 to coordinates, because 0 is flag for unmappable.
            if strand_y == "-":
                invert = True
                # no +1, because already one past current residue (due to open
                # bracket)
                y = int(size_y) - int(first_y)
            else:
                invert = False
                y = int(first_y) + 1

            if chr_x != chromosome:
                keep = False
            else:
                keep = True
                if options.loglevel >= 3:
                    print "# adding alignment", line[:-1]

            continue

        elif line.strip() == "":
            keep = False
            continue

        elif keep:

            data = map(int, line[:-1].split("\t"))

            if len(data) == 3:
                size, increment_x, increment_y = data
            else:
                size, increment_x, increment_y = data[0], 0, 0

            # add position
            if invert:
                map_position[x:x + size] = numpy.arrayrange(y, y - size, -1)
            else:
                map_position[x:x + size] = numpy.arrayrange(y, y + size, 1)

            if chr_y not in map_id2chromosome:
                map_chromosome2id[chr_y] = len(map_id2chromosome)
                map_id2chromosome.append(chr_y)

            id = map_chromosome2id[chr_y]
            if strand_y == "-":
                id = -id

            # add chromsome
            map_chromosome[x:x + size] = id

            x += increment_x + size
            if invert:
                y -= increment_y + size
            else:
                y += increment_y + size

            if y < 0:
                raise "illegal mapping: %i -> %i for %s %s:%s-%s(%s) to %s %s: %s-%s(%s)" % (
                    x, y, chr_x, strand_x, first_x, last_x, size_x, chr_y,
                    strand_y, first_y, last_y, size_y)

    return map_position, map_chromosome, map_chromosome2id, map_id2chromosome
Example #23
0
def main(argv):
    frmt = None
    src_filename = None
    dst_filename = None
    out_bands = 3
    band_number = 1

    gdal.AllRegister()
    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        sys.exit(0)

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-of' or arg == '-f':
            i = i + 1
            frmt = argv[i]

        elif arg == '-b':
            i = i + 1
            band_number = int(argv[i])

        elif arg == '-rgba':
            out_bands = 4

        elif src_filename is None:
            src_filename = argv[i]

        elif dst_filename is None:
            dst_filename = argv[i]

        else:
            Usage()

        i = i + 1

    if dst_filename is None:
        Usage()

    # ----------------------------------------------------------------------------
    # Open source file

    src_ds = gdal.Open(src_filename)
    if src_ds is None:
        print('Unable to open %s ' % src_filename)
        sys.exit(1)

    src_band = src_ds.GetRasterBand(band_number)

    # ----------------------------------------------------------------------------
    # Ensure we recognise the driver.

    if frmt is None:
        frmt = GetOutputDriverFor(dst_filename)

    dst_driver = gdal.GetDriverByName(frmt)
    if dst_driver is None:
        print('"%s" driver not registered.' % frmt)
        sys.exit(1)

    # ----------------------------------------------------------------------------
    # Build color table.

    ct = src_band.GetRasterColorTable()

    ct_size = ct.GetCount()
    lookup = [
        Numeric.arrayrange(ct_size),
        Numeric.arrayrange(ct_size),
        Numeric.arrayrange(ct_size),
        Numeric.ones(ct_size) * 255
    ]

    if ct is not None:
        for i in range(ct_size):
            entry = ct.GetColorEntry(i)
            for c in range(4):
                lookup[c][i] = entry[c]

    # ----------------------------------------------------------------------------
    # Create the working file.

    if frmt == 'GTiff':
        tif_filename = dst_filename
    else:
        tif_filename = 'temp.tif'

    gtiff_driver = gdal.GetDriverByName('GTiff')

    tif_ds = gtiff_driver.Create(tif_filename, src_ds.RasterXSize,
                                 src_ds.RasterYSize, out_bands)

    # ----------------------------------------------------------------------------
    # We should copy projection information and so forth at this point.

    tif_ds.SetProjection(src_ds.GetProjection())
    tif_ds.SetGeoTransform(src_ds.GetGeoTransform())
    if src_ds.GetGCPCount() > 0:
        tif_ds.SetGCPs(src_ds.GetGCPs(), src_ds.GetGCPProjection())

    # ----------------------------------------------------------------------------
    # Do the processing one scanline at a time.

    progress(0.0)
    for iY in range(src_ds.RasterYSize):
        src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)

        for iBand in range(out_bands):
            band_lookup = lookup[iBand]

            dst_data = Numeric.take(band_lookup, src_data)
            tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)

        progress((iY + 1.0) / src_ds.RasterYSize)

    tif_ds = None

    # ----------------------------------------------------------------------------
    # Translate intermediate file to output format if desired format is not TIFF.

    if tif_filename != dst_filename:
        tif_ds = gdal.Open(tif_filename)
        dst_driver.CreateCopy(dst_filename, tif_ds)
        tif_ds = None

        gtiff_driver.Delete(tif_filename)
Example #24
0
# ----------------------------------------------------------------------------
# Ensure we recognise the driver.

dst_driver = gdal.GetDriverByName(format)
if dst_driver is None:
    print('"%s" driver not registered.' % format)
    sys.exit(1)

# ----------------------------------------------------------------------------
# Build color table.

ct = src_band.GetRasterColorTable()

ct_size = ct.GetCount()
lookup = [Numeric.arrayrange(ct_size),
          Numeric.arrayrange(ct_size),
          Numeric.arrayrange(ct_size),
          Numeric.ones(ct_size) * 255]

if ct is not None:
    for i in range(ct_size):
        entry = ct.GetColorEntry(i)
        for c in range(4):
            lookup[c][i] = entry[c]

# ----------------------------------------------------------------------------
# Create the working file.

if format == 'GTiff':
    tif_filename = dst_filename
Example #25
0
# Adapted for numpy/ma/cdms2 by convertcdms.py
import numpy
# Tutorial for xmgrace module, using Numeric only

# it is recomended to run it usibng parser.py or just read it

print 'it is recomended to run this file using parser.py or just read it'

TEMPDIR = './'

# First let's create some data
npoints = 50
X = numpy.arrayrange(npoints, dtype='d')
X = X / float(npoints) * 2. * numpy.pi

Y1 = numpy.ma.sin(X)
Y2 = numpy.ma.cos(X)
Y3 = numpy.ma.tan(X)

# Now the real grace thing, plot the 2 on one graph and the diff on
# another graph

from genutil import xmgrace  # first we need to import xmgrace module

x = xmgrace.init()  # create our xmgrace object

# First let's set our graphs area
# graph 0, exist by default, but we need to add 1 graph, therefore:
x.add_graph()  # adds one graph to our graph list (x.Graph)

# Let's change the orientation of the page to portrait
# Adapted for numpy/ma/cdms2 by convertcdms.py
import numpy
# Tutorial for xmgrace module, using Numeric only

# it is recomended to run it usibng parser.py or just read it

print 'it is recomended to run this file using parser.py or just read it'

TEMPDIR = './'

# First let's create some data
npoints = 50
X = numpy.arrayrange(npoints, dtype='d')
X = X / float(npoints) * 2. * numpy.pi

Y1 = numpy.ma.sin(X)
Y2 = numpy.ma.cos(X)
Y3 = numpy.ma.tan(X)

# Now the real grace thing, plot the 2 on one graph and the diff on another graph

from genutil import xmgrace  # first we need to import xmgrace module

x = xmgrace.init()  # create our xmgrace object

# First let's set our graphs area
# graph 0, exist by default, but we need to add 1 graph, therefore:
x.add_graph()  # adds one graph to our graph list (x.Graph)

# Let's change the orientation of the page to portrait
x.portrait()