<commit_before>import os
import sys

import gdal
import osr
import numpy
import pyproj

from invest_natcap import raster_utils

BIOMASS_PREFIXES = ['am', 'af', 'as']
DATA_DIR = os.path.join("C:\\", "Users", "rich", "Desktop")
OUTPUT_DIR = os.path.join("C:\\", "Users", "rich", "Desktop", "forest_edge_output")
BIOMASS_BASE = '_biov2ct1.tif'
LULC_BASE = '.tif'
FOREST_LULCS = [1, 2, 3, 4, 5]

if __name__ == '__main__':
    #mask out forest LULCs
    raster_utils.create_directories([OUTPUT_DIR])

    pantropic_regions = ['am', 'af', 'as']
    ecoregion_headers = ['ECO_NAME', 'ECODE_NAME', 'WWF_MHTNAM']

    ecoregion_shapefile_uri = os.path.join(
            DATA_DIR, 'ecoregions', 'ecoregions_projected.shp')

    ecoregion_lookup = raster_utils.extract_datasource_table_by_key(
        ecoregion_shapefile_uri, 'ECO_ID_U')
    ecoregion_nodata = -1
    ecoregion_lookup[ecoregion_nodata] = {
        'ECO_NAME': 'UNKNOWN',
        'ECODE_NAME': 'UNKNOWN',
        'WWF_MHTNAM': 'UNKNOWN',
        }

    for prefix in pantropic_regions:
        lulc_raw_uri = os.path.join(DATA_DIR, '%s%s' % (prefix, LULC_BASE))
        biomass_raw_uri = os.path.join(DATA_DIR, '%s%s' % (prefix, BIOMASS_BASE))

        cell_size = raster_utils.get_cell_size_from_uri(lulc_raw_uri)

        lulc_uri = os.path.join(OUTPUT_DIR, "%s_lulc_aligned.tif" % (prefix))
        biomass_uri = os.path.join(OUTPUT_DIR, "%s_biomass_aligned.tif" % (prefix))

        raster_utils.align_dataset_list(
            [lulc_raw_uri, biomass_raw_uri], [lulc_uri, biomass_uri], ['nearest']*2,
            cell_size, 'intersection', 0, dataset_to_bound_index=None,
            aoi_uri=None, assert_datasets_projected=True, process_pool=None)

        #create ecoregion id
        ecoregion_dataset_uri = os.path.join(
            OUTPUT_DIR, "%s_ecoregion_id.tif" % (prefix))
        'raster_utils.new_raster_from_base_uri(
            lulc_uri, ecoregion_dataset_uri, 'GTiff', ecoregion_nodata, gdal.GDT_Int16)
        raster_utils.rasterize_layer_uri(
            ecoregion_dataset_uri, ecoregion_shapefile_uri,
            option_list=["ATTRIBUTE=ECO_ID_U"])

        ecoregion_dataset = gdal.Open(ecoregion_dataset_uri)
        ecoregion_band = ecoregion_dataset.GetRasterBand(1)

        lulc_nodata = raster_utils.get_nodata_from_uri(lulc_uri)
        biomass_nodata = raster_utils.get_nodata_from_uri(biomass_uri)

        forest_lulc_codes = [1, 2, 3, 4, 5]

        mask_uri = os.path.join(OUTPUT_DIR, "%s_mask.tif" % prefix)
        mask_nodata = 2

        def mask_nonforest(lulc):
            mask = numpy.empty(lulc.shape, dtype=numpy.int8)
            mask[:] = 1
            for lulc_code in forest_lulc_codes:
                mask[lulc == lulc_code] = 0
            mask[lulc == lulc_nodata] = mask_nodata
            return mask

        raster_utils.vectorize_datasets(
            [lulc_uri,], mask_nonforest, mask_uri, gdal.GDT_Byte,
            mask_nodata, cell_size, 'intersection', dataset_to_align_index=0,
            dataset_to_bound_index=None, aoi_uri=None,
            assert_datasets_projected=True, process_pool=None, vectorize_op=False,
            datasets_are_pre_aligned=True)

        forest_edge_distance_uri = os.path.join(OUTPUT_DIR, "%s_forest_edge.tif" % prefix)
        raster_utils.distance_transform_edt(mask_uri, forest_edge_distance_uri)

        forest_edge_nodata = raster_utils.get_nodata_from_uri(forest_edge_distance_uri)
        biomass_stats_uri = os.path.join(OUTPUT_DIR,  "%s_biomass_stats.csv" % prefix)
        outfile = open(biomass_stats_uri, 'w')

        biomass_ds = gdal.Open(biomass_uri, gdal.GA_ReadOnly)
        biomass_band = biomass_ds.GetRasterBand(1)

        forest_edge_distance_ds = gdal.Open(forest_edge_distance_uri)
        forest_edge_distance_band = forest_edge_distance_ds.GetRasterBand(1)

        n_rows, n_cols = raster_utils.get_row_col_from_uri(biomass_uri)

        base_srs = osr.SpatialReference(biomass_ds.GetProjection())
        lat_lng_srs = base_srs.CloneGeogCS()
        coord_transform = osr.CoordinateTransformation(
            base_srs, lat_lng_srs)
        gt = biomass_ds.GetGeoTransform()

        for row_index in xrange(n_rows):
            print row_index, n_rows
            biomass_row = biomass_band.ReadAsArray(0, row_index, n_cols, 1)
            forest_edge_distance_row = forest_edge_distance_band.ReadAsArray(
                0, row_index, n_cols, 1)
            ecoregion_id_row = ecoregion_band.ReadAsArray(
                0, row_index, n_cols, 1)
            row_coord = gt[3] + row_index * gt[5]
            for col_index in xrange(n_cols):
                col_coord = gt[0] + col_index * gt[1]
                lng_coord, lat_coord, _ = coord_transform.TransformPoint(
                    col_coord, row_coord)
                ecoregion_id = ecoregion_id_row[0, col_index]
                if forest_edge_distance_row[0, col_index] != forest_edge_nodata and forest_edge_distance_row[0, col_index] > 0.0 and biomass_row[0, col_index] != biomass_nodata:
                    outfile.write("%f,%f,%f,%f,%s,%s,%s\n" % (forest_edge_distance_row[0, col_index] * cell_size, biomass_row[0, col_index], lat_coord, lng_coord, ecoregion_lookup[ecoregion_id]['ECO_NAME'], ecoregion_lookup[ecoregion_id]['ECODE_NAME'], ecoregion_lookup[ecoregion_id]['WWF_MHTNAM']))

    raster_utils.email_report(
        "done with global_carbon_edge_effect.py", "3152624786@txt.att.net")<commit_msg>typo<commit_after>import os
import sys

import gdal
import osr
import numpy
import pyproj

from invest_natcap import raster_utils

BIOMASS_PREFIXES = ['am', 'af', 'as']
DATA_DIR = os.path.join("C:\\", "Users", "rich", "Desktop")
OUTPUT_DIR = os.path.join("C:\\", "Users", "rich", "Desktop", "forest_edge_output")
BIOMASS_BASE = '_biov2ct1.tif'
LULC_BASE = '.tif'
FOREST_LULCS = [1, 2, 3, 4, 5]

if __name__ == '__main__':
    #mask out forest LULCs
    raster_utils.create_directories([OUTPUT_DIR])

    pantropic_regions = ['am', 'af', 'as']
    ecoregion_headers = ['ECO_NAME', 'ECODE_NAME', 'WWF_MHTNAM']

    ecoregion_shapefile_uri = os.path.join(
            DATA_DIR, 'ecoregions', 'ecoregions_projected.shp')

    ecoregion_lookup = raster_utils.extract_datasource_table_by_key(
        ecoregion_shapefile_uri, 'ECO_ID_U')
    ecoregion_nodata = -1
    ecoregion_lookup[ecoregion_nodata] = {
        'ECO_NAME': 'UNKNOWN',
        'ECODE_NAME': 'UNKNOWN',
        'WWF_MHTNAM': 'UNKNOWN',
        }

    for prefix in pantropic_regions:
        lulc_raw_uri = os.path.join(DATA_DIR, '%s%s' % (prefix, LULC_BASE))
        biomass_raw_uri = os.path.join(DATA_DIR, '%s%s' % (prefix, BIOMASS_BASE))

        cell_size = raster_utils.get_cell_size_from_uri(lulc_raw_uri)

        lulc_uri = os.path.join(OUTPUT_DIR, "%s_lulc_aligned.tif" % (prefix))
        biomass_uri = os.path.join(OUTPUT_DIR, "%s_biomass_aligned.tif" % (prefix))

        raster_utils.align_dataset_list(
            [lulc_raw_uri, biomass_raw_uri], [lulc_uri, biomass_uri], ['nearest']*2,
            cell_size, 'intersection', 0, dataset_to_bound_index=None,
            aoi_uri=None, assert_datasets_projected=True, process_pool=None)

        #create ecoregion id
        ecoregion_dataset_uri = os.path.join(
            OUTPUT_DIR, "%s_ecoregion_id.tif" % (prefix))
        raster_utils.new_raster_from_base_uri(
            lulc_uri, ecoregion_dataset_uri, 'GTiff', ecoregion_nodata, gdal.GDT_Int16)
        raster_utils.rasterize_layer_uri(
            ecoregion_dataset_uri, ecoregion_shapefile_uri,
            option_list=["ATTRIBUTE=ECO_ID_U"])

        ecoregion_dataset = gdal.Open(ecoregion_dataset_uri)
        ecoregion_band = ecoregion_dataset.GetRasterBand(1)

        lulc_nodata = raster_utils.get_nodata_from_uri(lulc_uri)
        biomass_nodata = raster_utils.get_nodata_from_uri(biomass_uri)

        forest_lulc_codes = [1, 2, 3, 4, 5]

        mask_uri = os.path.join(OUTPUT_DIR, "%s_mask.tif" % prefix)
        mask_nodata = 2

        def mask_nonforest(lulc):
            mask = numpy.empty(lulc.shape, dtype=numpy.int8)
            mask[:] = 1
            for lulc_code in forest_lulc_codes:
                mask[lulc == lulc_code] = 0
            mask[lulc == lulc_nodata] = mask_nodata
            return mask

        raster_utils.vectorize_datasets(
            [lulc_uri,], mask_nonforest, mask_uri, gdal.GDT_Byte,
            mask_nodata, cell_size, 'intersection', dataset_to_align_index=0,
            dataset_to_bound_index=None, aoi_uri=None,
            assert_datasets_projected=True, process_pool=None, vectorize_op=False,
            datasets_are_pre_aligned=True)

        forest_edge_distance_uri = os.path.join(OUTPUT_DIR, "%s_forest_edge.tif" % prefix)
        raster_utils.distance_transform_edt(mask_uri, forest_edge_distance_uri)

        forest_edge_nodata = raster_utils.get_nodata_from_uri(forest_edge_distance_uri)
        biomass_stats_uri = os.path.join(OUTPUT_DIR,  "%s_biomass_stats.csv" % prefix)
        outfile = open(biomass_stats_uri, 'w')

        biomass_ds = gdal.Open(biomass_uri, gdal.GA_ReadOnly)
        biomass_band = biomass_ds.GetRasterBand(1)

        forest_edge_distance_ds = gdal.Open(forest_edge_distance_uri)
        forest_edge_distance_band = forest_edge_distance_ds.GetRasterBand(1)

        n_rows, n_cols = raster_utils.get_row_col_from_uri(biomass_uri)

        base_srs = osr.SpatialReference(biomass_ds.GetProjection())
        lat_lng_srs = base_srs.CloneGeogCS()
        coord_transform = osr.CoordinateTransformation(
            base_srs, lat_lng_srs)
        gt = biomass_ds.GetGeoTransform()

        for row_index in xrange(n_rows):
            print row_index, n_rows
            biomass_row = biomass_band.ReadAsArray(0, row_index, n_cols, 1)
            forest_edge_distance_row = forest_edge_distance_band.ReadAsArray(
                0, row_index, n_cols, 1)
            ecoregion_id_row = ecoregion_band.ReadAsArray(
                0, row_index, n_cols, 1)
            row_coord = gt[3] + row_index * gt[5]
            for col_index in xrange(n_cols):
                col_coord = gt[0] + col_index * gt[1]
                lng_coord, lat_coord, _ = coord_transform.TransformPoint(
                    col_coord, row_coord)
                ecoregion_id = ecoregion_id_row[0, col_index]
                if forest_edge_distance_row[0, col_index] != forest_edge_nodata and forest_edge_distance_row[0, col_index] > 0.0 and biomass_row[0, col_index] != biomass_nodata:
                    outfile.write("%f,%f,%f,%f,%s,%s,%s\n" % (forest_edge_distance_row[0, col_index] * cell_size, biomass_row[0, col_index], lat_coord, lng_coord, ecoregion_lookup[ecoregion_id]['ECO_NAME'], ecoregion_lookup[ecoregion_id]['ECODE_NAME'], ecoregion_lookup[ecoregion_id]['WWF_MHTNAM']))

    raster_utils.email_report(
        "done with global_carbon_edge_effect.py", "3152624786@txt.att.net")<|endoftext|>


<commit_before>from django.contrib.contenttypes.models import ContentType
from django.shortcuts import redirect

from .models import SlugRedirect

class SlugRedirectMixin(object):
    """Adds SlugRedirect redirection for DetailView-derived classes"""

    def redirect_to(self, correct_object):
        return redirect(correct_object)

    def get(self, request, *args, **kwargs):
        # Check if this is old slug for redirection:
        slug = kwargs['slug']
        try:
            sr = SlugRedirect.objects.get(
                content_type=ContentType.objects.get_for_model(self.model),
                old_object_slug=slug
            )
            return self.redirect_to(sr.new_object)
        # Otherwise look up the slug as normal:
        except SlugRedirect.DoesNotExist:
            return super(SlugRedirectMixin, self).get(request, *args, **kwargs)
<commit_msg>Factor out get_slug_redirect for use in non-class-based-views<commit_after>from django.contrib.contenttypes.models import ContentType
from django.shortcuts import redirect

from .models import SlugRedirect

def get_slug_redirect(model, slug):
    try:
        sr = SlugRedirect.objects.get(
            content_type=ContentType.objects.get_for_model(model),
            old_object_slug=slug
        )
        return sr.new_object
    except SlugRedirect.DoesNotExist:
        return None

class SlugRedirectMixin(object):
    """Adds SlugRedirect redirection for DetailView-derived classes"""

    def redirect_to(self, correct_object):
        return redirect(correct_object)

    def get(self, request, *args, **kwargs):
        # Check if this is an old slug for redirection:
        slug = kwargs['slug']
        object_to_redirect_to = get_slug_redirect(self.model, slug)
        if object_to_redirect_to:
            return self.redirect_to(object_to_redirect_to)
        # Otherwise look up the slug as normal:
        else:
            return super(SlugRedirectMixin, self).get(request, *args, **kwargs)
<|endoftext|>


<commit_before>from opcode import opname
from opcode import cmp_op
from compiler.ast import *

from student import *

debug = 1
class Code:
    def __init__(self, code, op_count=None):
        self.code = code.co_code
        self.varnames = code.co_varnames
        self.names = code.co_names
        self.consts = code.co_consts
        self.freevars = code.co_freevars
        self.counter = op_count
        self.i = 0
        self.cp = 0
        self.stop = len(self.code)
        self.indent=0
    def set_stop(self, n):
        if n:
            if debug:
                print "----- block started"
            self.stop = self.i + n
            self.indent = self.indent + 1
        else:
            self.stop = len(self.code)
            self.indent = self.indent - 1
    def get_nextop(self):
        if self.i < self.stop:
            oc = ord(self.code[self.i])
            on = opname[oc]
            self.cp = self.i
            self.i = self.i + 1
            return on
        else:
            raise StopIteration
    def get_arg(self):
        oparg = ord(self.code[self.i]) + ord(self.code[self.i+1]) * 256
        self.i = self.i + 2
        if debug:
            print "%d" % oparg
        return oparg
    def get_varname(self, n):
        return self.varnames[n]
    def get_name(self, n):
        return self.names[n]
    def get_const(self, n):
        return self.consts[n]
    def get_current_ip(self):
        return self.cp
    def get_deref(self, n):
        return self.freevars[n]

class Decompiler:
    def __init__(self, nesting = None):
        self.stack = []
        self.labels = {}
        self.last_label = 0
        self.text = []
        self.expr_inner = None
        self.assign = None
        self.ifs = None
        self.final_expr = None
        self.it = None
        if nesting is None:
            self.nesting = 0
        else:
            self.nesting = nesting + 1

    def decompile(self, code):
        try:
            while True:
                on = code.get_nextop()
                if debug:
                    print code.get_current_ip(), on,
                func = getattr(self, on)
                func(code)
                self.check_current_ip(code.get_current_ip())
        except StopIteration:
            if debug:
                print "----- block finished"

    def check_current_ip(self, ip):
        label = self.labels.get(ip)
        if label is not None:
            if len(self.stack) >= 2:
                while len(self.stack) >= 2:
                    tos, oper = self.stack.pop()
                    tos2, oper2 = self.stack.pop()
                    if debug:
                        print "get from stack TOS=", (tos, oper)
                        print "get from stack TOS1=", (tos2, oper2)
                    tos = "(%s) %s (%s)" % (tos2, oper2, tos)
                    #tos = "%s %s %s" % (tos2, oper2, tos)
                    self.stack.append((tos, oper))
                    if debug:
                        print "new TOS=", (tos, oper)
                tos, oper = self.stack[-1]
                tos = "(%s)" % tos
                self.stack[-1]=(tos, oper)

    def BINARY_MULTIPLY(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s * %s' % (oper1, oper2)
        self.stack.append(expr)

    def BUILD_TUPLE(self, code):
        oparg = code.get_arg()
        t = [str(self.stack.pop()) for i in range(oparg)]
        t.reverse()
        self.stack.append("(%s)" % ", ".join(t))

    def COMPARE_OP(self, code):
        oparg = code.get_arg()
        op = cmp_op[oparg]
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        #how to check if oper is digit or string?
        expr = "%s %s %s" % (oper1, op, oper2)
        self.stack.append(expr)
        if debug:
            print "--PUSH EXPR=", expr

    def FOR_ITER(self, code):
        oparg = code.get_arg()
        code.set_stop(oparg + 1)   # include POP_BLOCK
        self.it = self.stack.pop()
        print "iter=", self.it
        #d = Decompiler()
        #d.decompile(code)
        #code.set_stop(None)

    def GET_ITER(self, code):
        pass

    def JUMP_ABSOLUTE(self, code):
        oparg = code.get_arg()

    def JUMP_IF_FALSE(self, code):
        oparg = code.get_arg()
        cmp = self.stack[-1]
        expr = (cmp, 'and')
        self.stack[-1] = expr
        target = oparg + code.get_current_ip() + 3
        gr = self.labels.setdefault(target, 1)
        self.last_label = target

    def JUMP_IF_TRUE(self, code):
        oparg = code.get_arg()
        cmp = self.stack[-1]
        expr = (cmp, 'or')
        self.stack[-1] = expr
        target = oparg + code.get_current_ip() + 3
        gr = self.labels.setdefault(target, 1)
        self.last_label = target

    def LOAD_ATTR(self, code):
        oparg = code.get_arg()
        varname = code.get_name(oparg)
        tos = self.stack.pop()
        tos = '%s.%s' % (tos, varname)
        self.stack.append(tos)

    def LOAD_CONST(self, code):
        oparg = code.get_arg()
        const = str(code.get_const(oparg))
        if not const.isdigit():
            const = "'%s'" % const
        self.stack.append(const)

    def LOAD_DEREF(self, code):
        oparg = code.get_arg()
        varname = code.get_deref(oparg)
        self.stack.append(varname)

    def LOAD_FAST(self, code):
        oparg = code.get_arg()
        varname = code.get_varname(oparg)
        self.stack.append(varname)

    def LOAD_GLOBAL(self, code):
        oparg = code.get_arg()
        name = code.get_name(oparg)
        self.stack.append(name)

    def SETUP_LOOP(self, code):
        oparg = code.get_arg()
        code.set_stop(oparg + 1) # include POP_BLOCK
        d = Decompiler(self.nesting)
        d.decompile(code)
        if debug:
            print "expr_inner =", d.expr_inner
            print "    assign =", d.assign
            print "      iter =", d.it
            print "       ifs =", d.ifs
        self.expr_inner = d.expr_inner
        expr =  "for %s in %s" %(d.assign, d.it)
        if d.ifs:
            expr = "%s if %s" % (expr, d.ifs)
        if self.nesting == 0:
            expr = "%s %s" % (self.expr_inner, expr)
        self.final_expr = expr
        if d.final_expr is not None:
            self.final_expr = "%s %s" % (self.final_expr, d.final_expr)
        if debug:
            print "nesting=", self.nesting
            print "for expr =", self.final_expr
            print "labels =", self.labels
            print "self.expr=", self.final_expr
            print "d.final_expr=", d.final_expr
        code.set_stop(None)

    def STORE_FAST(self, code):
        oparg = code.get_arg()
        varname = code.get_varname(oparg)
        self.assign = varname # for 'varname'
        node = AssName(varname, 'OP_ASSIGN')

    def POP_BLOCK(self, code):
        if debug:
            print ""
        if len(self.stack) > 0:
            ifexpr, op = self.stack.pop()
            self.ifs = ifexpr
            if debug:
                print "if expr = ", ifexpr

    def POP_TOP(self, code):
        if debug:
            print ""

    def RETURN_VALUE(self, code):
        if debug:
            print ""

    def YIELD_VALUE(self, code):
        self.expr_inner = self.stack.pop()
        if debug:
            print ""
        if self.last_label:
            if debug:
                print "check_current_ip(%s)" % self.last_label
            self.check_current_ip(self.last_label)

def decompile_tostring(g):
	code = Code(g.gi_frame.f_code)
	d = Decompiler()
	d.decompile(code)
	return d.final_expr

def ttest():
    #g = (s for s in Student)
    g = (a for b in Student if c > d)
    g = (a for b in Student if c > d for e in Student if f < g)
    #g = (s for s in Student if s.age > 20 and (s.group.number == 4142 or 'FFF' in s.marks.subject.name))
    #g = ( (s,d,w) for t in Student if ((4 != x.a) or (a * 3 > 20) or (a * 2 < 5) and (a * 8 == 20)))
    #g = ( (s,d,w) for t in Student   if ( 4 != x.a  or  a * 3 > 20 ) and ( a * 2 < 5  or  a * 8 == 20 ))
    #g = ( (s,d,w) for t in Student if (((4 != x.a) or (a * 3 > 20)) and (a * 2 < 5) ))
    #g = ( (s,d,w) for t in Student if ((4 != x.a) or (a * 3 > 20) and (a * 2 < 5) ))
    #g = ( (s,d,w) for t in Student if ((4 != x.amount or amount * 3 > 20 or amount * 2 < 5) and (amount * 8 == 20)))
    #g = ( (s,t,w) for t in Student if ((4 != x.a.b or a * 3 > 20 or a * 2 < 5 and v == 6) and a * 8 == 20 or (f > 4) ))
    #g = (s for t in Student if a == 5)
    #g = (s for s in Student if a == 5 for f in Student if t > 4 )
    code = Code(g.gi_frame.f_code)
    d = Decompiler()
    d.decompile(code)

ttest()<commit_msg>decompiler updated<commit_after>from opcode import opname
from opcode import cmp_op
from compiler.ast import *

from student import *

debug = 1
class Code:
    def __init__(self, code, op_count=None):
        self.code = code.co_code
        self.varnames = code.co_varnames
        self.names = code.co_names
        self.consts = code.co_consts
        self.freevars = code.co_freevars
        self.counter = op_count
        self.i = 0
        self.cp = 0
        self.stop = len(self.code)
        self.indent=0
        self.currentop = None
    def set_stop(self, n):
        if n:
            if debug:
                print "----- block started"
            self.stop = self.i + n
            self.indent = self.indent + 1
        else:
            self.stop = len(self.code)
            self.indent = self.indent - 1
    def get_nextop(self):
        if self.i < self.stop:
            oc = ord(self.code[self.i])
            self.currentop = opname[oc]
            self.cp = self.i
            self.i = self.i + 1
            return self.currentop
        else:
            raise StopIteration
    def get_currentop(self):
        return self.currentop
    def get_arg(self):
        oparg = ord(self.code[self.i]) + ord(self.code[self.i+1]) * 256
        self.i = self.i + 2
        if debug:
            print "%d" % oparg
        return oparg
    def get_varname(self, n):
        return self.varnames[n]
    def get_name(self, n):
        return self.names[n]
    def get_const(self, n):
        return self.consts[n]
    def get_current_ip(self):
        return self.cp
    def get_deref(self, n):
        return self.freevars[n]

class Decompiler:
    def __init__(self, nesting = None):
        self.stack = []
        self.labels = {}
        self.last_label = 0
        self.text = []
        self.expr_inner = None
        self.assign = None
        self.ifs = None
        self.final_expr = None
        self.it = None
        if nesting is None:
            self.nesting = 0
        else:
            self.nesting = nesting + 1

    def decompile(self, code):
        try:
            while True:
                on = code.get_nextop()
                if debug:
                    print code.get_current_ip(), on,
                on = on.replace('+', '_')
                func = getattr(self, on)
                func(code)
                self.check_current_ip(code.get_current_ip())
        except StopIteration:
            if debug:
                print "----- block finished"

    def check_current_ip(self, ip):
        label = self.labels.get(ip)
        if label is not None:
            if len(self.stack) >= 2:
                while len(self.stack) >= 2:
                    tos, oper = self.stack.pop()
                    tos2, oper2 = self.stack.pop()
                    if debug:
                        print "get from stack TOS=", (tos, oper)
                        print "get from stack TOS1=", (tos2, oper2)
                    tos = "(%s) %s (%s)" % (tos2, oper2, tos)
                    #tos = "%s %s %s" % (tos2, oper2, tos)
                    self.stack.append((tos, oper))
                    if debug:
                        print "new TOS=", (tos, oper)
                tos, oper = self.stack[-1]
                tos = "(%s)" % tos
                self.stack[-1]=(tos, oper)

    def BINARY_POWER(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s ** %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_MULTIPLY(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s * %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_DIVIDE(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s / %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_FLOOR_DIVIDE(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s // %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_ADD(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s + %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_SUBSTRACT(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s - %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_SUBSCR(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s[%s]' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_LSHIFT(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s << %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_RSHIFT(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s >> %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_AND(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s & %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_XOR(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s ^ %s' % (oper1, oper2)
        self.stack.append(expr)

    def BINARY_OR(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s | %s' % (oper1, oper2)
        self.stack.append(expr)

    BINARY_TRUE_DIVIDE = BINARY_DIVIDE

    def BINARY_MODULO(self, code):
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        expr = '%s % %s' % (oper1, oper2)
        self.stack.append(expr)

    def BUILD_LIST(self, code):
        oparg = code.get_arg()
        t = [str(self.stack.pop()) for i in range(oparg)]
        t.reverse()
        self.stack.append("[%s]" % ", ".join(t))

    def BUILD_TUPLE(self, code):
        oparg = code.get_arg()
        t = [str(self.stack.pop()) for i in range(oparg)]
        t.reverse()
        self.stack.append("(%s)" % ", ".join(t))

    def CALL_FUNCTION(self, code):
        currentop = code.get_currentop()
        oparg = code.get_arg()
        kwarg, posarg = divmod(oparg, 256)
        args = []
        if debug:
            print "posarg=%s kwarg=%s" % (posarg, kwarg)
        if currentop in ('CALL_FUNCTION_KW','CALL_FUNCTION_VAR_KW'):
            args.insert(0, "**%s" % self.stack.pop())
        if currentop in ('CALL_FUNCTION_VAR','CALL_FUNCTION_VAR_KW'):
            args.insert(0, "*%s" % self.stack.pop())
        for i in range(kwarg):
            value = self.stack.pop()
            name = self.stack.pop()
            name = name[1:-1]
            args.insert(0, '%s=%s' % (name, value))
        for i in range(posarg):
            args.insert(0, "%s" % self.stack.pop())
        funcname = self.stack.pop()
        args = ", ".join(args)
        funccall = "%s(%s)" % (funcname, args)
        self.stack.append(funccall)
        if debug:
            print "FUNCTION CALL = %s" % funccall

    CALL_FUNCTION_VAR = CALL_FUNCTION
    CALL_FUNCTION_KW = CALL_FUNCTION
    CALL_FUNCTION_VAR_KW = CALL_FUNCTION

    def COMPARE_OP(self, code):
        oparg = code.get_arg()
        op = cmp_op[oparg]
        oper2 = self.stack.pop()
        oper1 = self.stack.pop()
        #how to check if oper is digit or string?
        expr = "%s %s %s" % (oper1, op, oper2)
        self.stack.append(expr)
        if debug:
            print "--PUSH EXPR=", expr

    def FOR_ITER(self, code):
        oparg = code.get_arg()
        code.set_stop(oparg + 1)   # include POP_BLOCK
        self.it = self.stack.pop()
        print "iter=", self.it

    def GET_ITER(self, code):
        pass

    def JUMP_ABSOLUTE(self, code):
        oparg = code.get_arg()

    JUMP_FORWARD = JUMP_ABSOLUTE
    def JUMP_IF_FALSE(self, code):
        oparg = code.get_arg()
        cmp = self.stack[-1]
        expr = (cmp, 'and')
        self.stack[-1] = expr
        target = oparg + code.get_current_ip() + 3
        gr = self.labels.setdefault(target, 1)
        self.last_label = target

    def JUMP_IF_TRUE(self, code):
        oparg = code.get_arg()
        cmp = self.stack[-1]
        expr = (cmp, 'or')
        self.stack[-1] = expr
        target = oparg + code.get_current_ip() + 3
        gr = self.labels.setdefault(target, 1)
        self.last_label = target

    def LOAD_ATTR(self, code):
        oparg = code.get_arg()
        varname = code.get_name(oparg)
        tos = self.stack.pop()
        tos = '%s.%s' % (tos, varname)
        self.stack.append(tos)

    def LOAD_CONST(self, code):
        oparg = code.get_arg()
        const = str(code.get_const(oparg))
        if not const.isdigit():
            const = "'%s'" % const
        if const == "'None'":
            const = "None"
        self.stack.append(const)

    def LOAD_DEREF(self, code):
        oparg = code.get_arg()
        varname = code.get_deref(oparg)
        self.stack.append(varname)

    def LOAD_FAST(self, code):
        oparg = code.get_arg()
        varname = code.get_varname(oparg)
        self.stack.append(varname)

    def LOAD_GLOBAL(self, code):
        oparg = code.get_arg()
        name = code.get_name(oparg)
        self.stack.append(name)

    LOAD_NAME = LOAD_GLOBAL

    def NOP(self, code):
        pass

    def POP_BLOCK(self, code):
        if debug:
            print ""
        if len(self.stack) > 0:
            ifexpr, op = self.stack.pop()
            self.ifs = ifexpr
            if debug:
                print "if expr = ", ifexpr

    def POP_TOP(self, code):
        if debug:
            print ""

    def RETURN_VALUE(self, code):
        if debug:
            print ""

    def SETUP_LOOP(self, code):
        oparg = code.get_arg()
        code.set_stop(oparg + 1) # include POP_BLOCK
        d = Decompiler(self.nesting)
        d.decompile(code)
        if debug:
            print "expr_inner =", d.expr_inner
            print "    assign =", d.assign
            print "      iter =", d.it
            print "       ifs =", d.ifs
        self.expr_inner = d.expr_inner
        expr =  "for %s in %s" %(d.assign, d.it)
        if d.ifs:
            expr = "%s if %s" % (expr, d.ifs)
        if self.nesting == 0:
            expr = "%s %s" % (self.expr_inner, expr)
        self.final_expr = expr
        if d.final_expr is not None:
            self.final_expr = "%s %s" % (self.final_expr, d.final_expr)
        if debug:
            print "nesting=", self.nesting
            print "for expr =", self.final_expr
            print "labels =", self.labels
            print "self.expr=", self.final_expr
            print "d.final_expr=", d.final_expr
        code.set_stop(None)

    def SLICE_0(self, code):
        tos = self.stack.pop()
        tos = "%s[:]" % tos
        self.stack.append(tos)

    def SLICE_1(self, code):
        tos = self.stack.pop()
        tos1 = self.stack.pop()
        tos = "%s[%s:]" % (tos1, tos)
        self.stack.append(tos)

    def SLICE_2(self, code):
        tos = self.stack.pop()
        tos1 = self.stack.pop()
        tos = "%s[:%s]" % (tos1, tos)
        self.stack.append(tos)

    def SLICE_3(self, code):
        tos = self.stack.pop()
        tos1 = self.stack.pop()
        tos2 = self.stack.pop()
        tos = "%s[%s:%s]" % (tos2, tos1, tos)
        self.stack.append(tos)

    def STORE_FAST(self, code):
        oparg = code.get_arg()
        varname = code.get_varname(oparg)
        self.assign = varname # for 'varname'
        node = AssName(varname, 'OP_ASSIGN')

    def UNARY_POSITIVE(self, code):
        self.stack.append("+%s" % self.stack.pop())

    def UNARY_NEGATIVE(self, code):
        self.stack.append("-%s" % self.stack.pop())

    def UNARY_NOT(self, code):
        self.stack.append("not %s" % self.stack.pop())

    def UNARY_CONVERT(self, code):
        self.stack.append("`%s`" % self.stack.pop())

    def UNARY_INVERT(self, code):
        self.stack.append("~%s" % self.stack.pop())

    def YIELD_VALUE(self, code):
        self.expr_inner = self.stack.pop()
        if debug:
            print ""
        if self.last_label:
            if debug:
                print "check_current_ip(%s)" % self.last_label
            self.check_current_ip(self.last_label)

def decompile_tostring(g):
	code = Code(g.gi_frame.f_code)
	d = Decompiler()
	d.decompile(code)
	return d.final_expr

def ttest():
    #g = (s for s in Student)
    #g = (a for b in Student if c > d)
    #g = (a for b in Student if c > d for e in Student if f < g)
    #g = (s for s in Student if s.age > 20 and (s.group.number == 4142 or 'FFF' in s.marks.subject.name))
    #g = ( (s,d,w) for t in Student if ((4 != x.a) or (a * 3 > 20) or (a * 2 < 5) and (a * 8 == 20)))
    #g = ( (s,d,w) for t in Student   if ( 4 != x.a  or  a * 3 > 20 ) and ( a * 2 < 5  or  a * 8 == 20 ))
    #g = ( (s,d,w) for t in Student if (((4 != x.a) or (a * 3 > 20)) and (a * 2 < 5) ))
    #g = ( (s,d,w) for t in Student if ((4 != x.a) or (a * 3 > 20) and (a * 2 < 5) ))
    #g = ( (s,d,w) for t in Student if ((4 != x.amount or amount * 3 > 20 or amount * 2 < 5) and (amount * 8 == 20)))
    #g = ( (s,t,w) for t in Student if ((4 != x.a.b or a * 3 > 20 or a * 2 < 5 and v == 6) and a * 8 == 20 or (f > 4) ))
    #g = (s for t in Student if a == 5)
    #g = (s for s in Student if a == 5 for f in Student if t > 4 )
    g = (func(a, a.attr, keyarg=123) for a in Student if a.method(x, *y, **z) is not None)
    g = (func(a, a.attr, b, b.c.d, keyarg1=123, keyarg2=456) for a in Student if a.method(x, x1, *y, **z) is not None)
    g = ([a, b, c] for a in [] if a > b)
    g = (a[:] for i in [])
    g = (a[b:] for i in [])
    g = (a[:b] for i in [])
    g = (a[b:c] for i in [])

    g = (a|b for i in [])
    #here add all binary ops

    g = (~a for i in [])
    #here add all unary ops

    code = Code(g.gi_frame.f_code)
    d = Decompiler()
    d.decompile(code)

ttest()<|endoftext|>


<commit_before>from decimal import Decimal, InvalidOperation
from datetime import datetime, date, time

import warnings
warnings.filterwarnings('ignore', '^Table.+already exists$', Warning, '^pony\\.orm\\.dbapiprovider$')

import MySQLdb
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG

from pony.utils import localbase
from pony.orm import dbschema
from pony.orm import dbapiprovider
from pony.orm.dbapiprovider import DBAPIProvider
from pony.orm.sqltranslation import SQLTranslator
from pony.orm.sqlbuilding import Value, SQLBuilder

class MySQLColumn(dbschema.Column):
    auto_template = '%(type)s PRIMARY KEY AUTO_INCREMENT'

class MySQLSchema(dbschema.DBSchema):
    column_class = MySQLColumn

class MyValue(Value):
    def quote_str(self, s):
        s = s.replace('%', '%%')
        return Value.quote_str(self, s)

class MySQLTranslator(SQLTranslator):
    dialect = 'MySQL'

class MySQLBuilder(SQLBuilder):
    dialect = 'MySQL'
    make_value = MyValue
    def YEAR(builder, expr):
        return 'year(', builder(expr), ')'
    def MONTH(builder, expr):
        return 'month(', builder(expr), ')'
    def DAY(builder, expr):
        return 'day(', builder(expr), ')'
    def HOUR(builder, expr):
        return 'hour(', builder(expr), ')'
    def MINUTE(builder, expr):
        return 'minute(', builder(expr), ')'
    def SECOND(builder, expr):
        return 'second(', builder(expr), ')'

def _string_sql_type(converter):
    db_encoding = converter.db_encoding or 'utf8'
    if converter.max_len:
        return 'VARCHAR(%d) CHARACTER SET %s' % (converter.max_len, db_encoding)
    return 'LONGTEXT CHARACTER SET %s' % db_encoding

class MySQLUnicodeConverter(dbapiprovider.UnicodeConverter):
    sql_type = _string_sql_type

class MySQLStrConverter(dbapiprovider.StrConverter):
    sql_type = _string_sql_type

class MySQLLongConverter(dbapiprovider.IntConverter):
    def sql_type(converter):
        return 'BIGINT'

class MySQLRealConverter(dbapiprovider.RealConverter):
    def sql_type(converter):
        return 'DOUBLE'

class MySQLBlobConverter(dbapiprovider.BlobConverter):
    def sql_type(converter):
        return 'LONGBLOB'

class MySQLProvider(DBAPIProvider):
    paramstyle = 'format'
    quote_char = "`"

    dbapi_module = MySQLdb
    dbschema_cls = MySQLSchema
    translator_cls = MySQLTranslator
    sqlbuilder_cls = MySQLBuilder

    converter_classes = [
        (bool, dbapiprovider.BoolConverter),
        (unicode, MySQLUnicodeConverter),
        (str, MySQLStrConverter),
        (int, dbapiprovider.IntConverter),
        (long, MySQLLongConverter),
        (float, MySQLRealConverter),
        (Decimal, dbapiprovider.DecimalConverter),
        (buffer, MySQLBlobConverter),
        (datetime, dbapiprovider.DatetimeConverter),
        (date, dbapiprovider.DateConverter)
    ]

    def _get_pool(provider, *args, **kwargs):
        if 'conv' not in kwargs:
            conv = MySQLdb.converters.conversions.copy()
            conv[FIELD_TYPE.BLOB] = [(FLAG.BINARY, buffer)]
            kwargs['conv'] = conv
        if 'charset' not in kwargs:
            kwargs['charset'] = 'utf8'
        return Pool(*args, **kwargs)

provider_cls = MySQLProvider

class Pool(localbase):
    def __init__(pool, *args, **kwargs): # called separately in each thread
        pool.args = args
        pool.kwargs = kwargs
        pool.con = None
    def connect(pool):
        if pool.con is None:
            pool.con = MySQLdb.connect(*pool.args, **pool.kwargs)
        return pool.con
    def release(pool, con):
        assert con is pool.con
        try: con.rollback()
        except:
            pool.close(con)
            raise
    def drop(pool, con):
        assert con is pool.con
        pool.con = None
        con.close()
<commit_msg>Bug fixed: MySQL uses CONCAT(a, b) instead of a || b for string concatenation<commit_after>from decimal import Decimal, InvalidOperation
from datetime import datetime, date, time

import warnings
warnings.filterwarnings('ignore', '^Table.+already exists$', Warning, '^pony\\.orm\\.dbapiprovider$')

import MySQLdb
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG

from pony.utils import localbase
from pony.orm import dbschema
from pony.orm import dbapiprovider
from pony.orm.dbapiprovider import DBAPIProvider
from pony.orm.sqltranslation import SQLTranslator
from pony.orm.sqlbuilding import Value, SQLBuilder, join

class MySQLColumn(dbschema.Column):
    auto_template = '%(type)s PRIMARY KEY AUTO_INCREMENT'

class MySQLSchema(dbschema.DBSchema):
    column_class = MySQLColumn

class MyValue(Value):
    def quote_str(self, s):
        s = s.replace('%', '%%')
        return Value.quote_str(self, s)

class MySQLTranslator(SQLTranslator):
    dialect = 'MySQL'

class MySQLBuilder(SQLBuilder):
    dialect = 'MySQL'
    make_value = MyValue
    def CONCAT(builder, *args):
        return 'concat(',  join(', ', map(builder, args)), ')'
    def YEAR(builder, expr):
        return 'year(', builder(expr), ')'
    def MONTH(builder, expr):
        return 'month(', builder(expr), ')'
    def DAY(builder, expr):
        return 'day(', builder(expr), ')'
    def HOUR(builder, expr):
        return 'hour(', builder(expr), ')'
    def MINUTE(builder, expr):
        return 'minute(', builder(expr), ')'
    def SECOND(builder, expr):
        return 'second(', builder(expr), ')'

def _string_sql_type(converter):
    db_encoding = converter.db_encoding or 'utf8'
    if converter.max_len:
        return 'VARCHAR(%d) CHARACTER SET %s' % (converter.max_len, db_encoding)
    return 'LONGTEXT CHARACTER SET %s' % db_encoding

class MySQLUnicodeConverter(dbapiprovider.UnicodeConverter):
    sql_type = _string_sql_type

class MySQLStrConverter(dbapiprovider.StrConverter):
    sql_type = _string_sql_type

class MySQLLongConverter(dbapiprovider.IntConverter):
    def sql_type(converter):
        return 'BIGINT'

class MySQLRealConverter(dbapiprovider.RealConverter):
    def sql_type(converter):
        return 'DOUBLE'

class MySQLBlobConverter(dbapiprovider.BlobConverter):
    def sql_type(converter):
        return 'LONGBLOB'

class MySQLProvider(DBAPIProvider):
    paramstyle = 'format'
    quote_char = "`"

    dbapi_module = MySQLdb
    dbschema_cls = MySQLSchema
    translator_cls = MySQLTranslator
    sqlbuilder_cls = MySQLBuilder

    converter_classes = [
        (bool, dbapiprovider.BoolConverter),
        (unicode, MySQLUnicodeConverter),
        (str, MySQLStrConverter),
        (int, dbapiprovider.IntConverter),
        (long, MySQLLongConverter),
        (float, MySQLRealConverter),
        (Decimal, dbapiprovider.DecimalConverter),
        (buffer, MySQLBlobConverter),
        (datetime, dbapiprovider.DatetimeConverter),
        (date, dbapiprovider.DateConverter)
    ]

    def _get_pool(provider, *args, **kwargs):
        if 'conv' not in kwargs:
            conv = MySQLdb.converters.conversions.copy()
            conv[FIELD_TYPE.BLOB] = [(FLAG.BINARY, buffer)]
            kwargs['conv'] = conv
        if 'charset' not in kwargs:
            kwargs['charset'] = 'utf8'
        return Pool(*args, **kwargs)

provider_cls = MySQLProvider

class Pool(localbase):
    def __init__(pool, *args, **kwargs): # called separately in each thread
        pool.args = args
        pool.kwargs = kwargs
        pool.con = None
    def connect(pool):
        if pool.con is None:
            pool.con = MySQLdb.connect(*pool.args, **pool.kwargs)
        return pool.con
    def release(pool, con):
        assert con is pool.con
        try: con.rollback()
        except:
            pool.close(con)
            raise
    def drop(pool, con):
        assert con is pool.con
        pool.con = None
        con.close()
<|endoftext|>


<commit_before># coding: utf-8

""" Description... """

from __future__ import division, print_function

__author__ = "adrn <adrn@astro.columbia.edu>"

# Standard library
import os, sys

# Third-party
import numpy as np
import astropy.units as u
from astropy.constants import G

from ..potential import *

__all__ = ["tidal_radius", "escape_velocity",
           "minimum_distance_matrix",
           "relative_normalized_coordinates",
           "generalized_variance"]

def tidal_radius(potential, satellite_orbit):
    """ Compute the tidal radius of the given satellite over the orbit
        or position provided.

        Parameters
        ----------
        potential : streams.CartesianPotential
        satellite_orbit : streams.Orbit
    """

    # assume the satellite has the right units already...
    #m_sat = satellite_orbit.m.value # 2.5E8 * u.M_sun
    m_sat = 2.5E8 #* u.M_sun

    # Radius of Sgr center relative to galactic center
    R_orbit = np.sqrt(np.sum(satellite_orbit._r**2., axis=-1))

    _G = 4.4997533243534949e-12 # kpc^3 / Myr^2 / M_sun

    m_halo_enc = potential["halo"]._parameters["v_halo"]**2 * R_orbit/_G
    m_enc = potential["disk"]._parameters["m"] + \
            potential["bulge"]._parameters["m"] + \
            m_halo_enc

    return R_orbit * (m_sat / m_enc)**(1./3)

def escape_velocity(potential, satellite_orbit, r_tide):
    """ Compute the escape velocity of a satellite in a potential given
        its tidal radius.

        Parameters
        ----------
        potential : streams.CartesianPotential
        satellite_orbit : streams.Particle
        r_tide : ndarray

    """

    # assume the satellite has the right units already...
    m_sat = satellite_orbit.m.value # 2.5E8 * u.M_sun

    _G = 4.4997533243534949e-12 # kpc^3 / Myr^2 / M_sun

    return np.sqrt(_G * m_sat / r_tide)

def relative_normalized_coordinates(potential, particle_orbits, satellite_orbit):
    """ Compute the coordinates of particles relative to the satellite,
        with positions normalized by the tidal radius and velocities
        normalized by the escape velocity.

        Note::
            Assumes the particle and satellite position/velocity
            units are the same!

        Parameters
        ----------
        potential : streams.CartesianPotential
        particle_orbits : OrbitCollection
        satellite_orbit : OrbitCollection
    """

    # need to add a new axis to normalize each coordinate component
    r_tide = tidal_radius(potential, satellite_orbit)[:,:,np.newaxis]
    v_esc = escape_velocity(potential, satellite_orbit, r_tide)

    return (particle_orbits._r - satellite_orbit._r) / r_tide, \
           (particle_orbits._v - satellite_orbit._v) / v_esc

def minimum_distance_matrix(potential, particle_orbits, satellite_orbit):
    """ Compute the Nx6 matrix of minimum phase-space distance vectors.

        Parameters
        ----------
        potential : Potential
        particle_orbits : OrbitCollection
        satellite_orbit : OrbitCollection
    """

    Nparticles = particle_orbits._r.shape[1]

    R,V = relative_normalized_coordinates(potential, particle_orbits, satellite_orbit)
    D_ps = np.sqrt(np.sum(R**2, axis=-1) + np.sum(V**2, axis=-1))

    # Find the index of the time of the minimum D_ps for each particle
    min_time_idx = D_ps.argmin(axis=0)

    min_ps = np.zeros((Nparticles,6))
    xx = zip(min_time_idx, range(Nparticles))
    for kk in range(Nparticles):
        jj,ii = xx[kk]
        min_ps[ii] = np.append(R[jj,ii], V[jj,ii])

    return min_ps

def generalized_variance(potential, particle_orbits, satellite_orbit):
    """ Compute the variance scalar that we will minimize.

        Parameters
        ----------
        potential : Potential
            The full Milky Way potential object.
        particle_orbits : OrbitCollection
            An object containing orbit information for a collection of
            particles.
        satellite_orbit : OrbitCollection
            Data for the Sgr satellite center, interpolated onto the
            time grid for our particles.
    """

    min_ps = minimum_distance_matrix(potential, particle_orbits, satellite_orbit)

    cov_matrix = np.cov(min_ps.T)
    # cov_matrix -> (6 x 6) covariance matrix for particles
    w,v = np.linalg.eig(cov_matrix)

    return np.sum(w)

<commit_msg>change input for tidal radius and esc vel functions<commit_after># coding: utf-8

""" Description... """

from __future__ import division, print_function

__author__ = "adrn <adrn@astro.columbia.edu>"

# Standard library
import os, sys

# Third-party
import numpy as np
import astropy.units as u
from astropy.constants import G

from ..potential import *

__all__ = ["tidal_radius", "escape_velocity",
           "minimum_distance_matrix",
           "relative_normalized_coordinates",
           "generalized_variance"]

def tidal_radius(potential, r, m_sat=2.5E8):
    """ Compute the tidal radius of the given satellite over the orbit
        or position provided.

        Parameters
        ----------
        potential : streams.CartesianPotential
        satellite_orbit : streams.Orbit
    """

    # assume the satellite has the right units already...

    # Radius of Sgr center relative to galactic center
    R_orbit = np.sqrt(np.sum(r**2., axis=-1))

    _G = 4.4997533243534949e-12 # kpc^3 / Myr^2 / M_sun

    m_halo_enc = potential["halo"]._parameters["v_halo"]**2 * R_orbit/_G
    m_enc = potential["disk"]._parameters["m"] + \
            potential["bulge"]._parameters["m"] + \
            m_halo_enc

    return R_orbit * (m_sat / m_enc)**(1./3)

def escape_velocity(potential, r_tide, m_sat):
    """ Compute the escape velocity of a satellite in a potential given
        its tidal radius.

        Parameters
        ----------
        potential : streams.CartesianPotential
        r_tide : ndarray

    """

    _G = 4.4997533243534949e-12 # kpc^3 / Myr^2 / M_sun

    return np.sqrt(_G * m_sat / r_tide)

def relative_normalized_coordinates(potential, particle_orbits, satellite_orbit):
    """ Compute the coordinates of particles relative to the satellite,
        with positions normalized by the tidal radius and velocities
        normalized by the escape velocity.

        Note::
            Assumes the particle and satellite position/velocity
            units are the same!

        Parameters
        ----------
        potential : streams.CartesianPotential
        particle_orbits : OrbitCollection
        satellite_orbit : OrbitCollection
    """

    # need to add a new axis to normalize each coordinate component
    r_tide = tidal_radius(potential, satellite_orbit._r)[:,:,np.newaxis]
    v_esc = escape_velocity(potential, r_tide, m_sat=satellite_orbit.m.value)

    return (particle_orbits._r - satellite_orbit._r) / r_tide, \
           (particle_orbits._v - satellite_orbit._v) / v_esc

def minimum_distance_matrix(potential, particle_orbits, satellite_orbit):
    """ Compute the Nx6 matrix of minimum phase-space distance vectors.

        Parameters
        ----------
        potential : Potential
        particle_orbits : OrbitCollection
        satellite_orbit : OrbitCollection
    """

    Nparticles = particle_orbits._r.shape[1]

    R,V = relative_normalized_coordinates(potential, particle_orbits, satellite_orbit)
    D_ps = np.sqrt(np.sum(R**2, axis=-1) + np.sum(V**2, axis=-1))

    # Find the index of the time of the minimum D_ps for each particle
    min_time_idx = D_ps.argmin(axis=0)

    min_ps = np.zeros((Nparticles,6))
    xx = zip(min_time_idx, range(Nparticles))
    for kk in range(Nparticles):
        jj,ii = xx[kk]
        min_ps[ii] = np.append(R[jj,ii], V[jj,ii])

    return min_ps

def generalized_variance(potential, particle_orbits, satellite_orbit):
    """ Compute the variance scalar that we will minimize.

        Parameters
        ----------
        potential : Potential
            The full Milky Way potential object.
        particle_orbits : OrbitCollection
            An object containing orbit information for a collection of
            particles.
        satellite_orbit : OrbitCollection
            Data for the Sgr satellite center, interpolated onto the
            time grid for our particles.
    """

    min_ps = minimum_distance_matrix(potential, particle_orbits, satellite_orbit)

    cov_matrix = np.cov(min_ps.T)
    # cov_matrix -> (6 x 6) covariance matrix for particles
    w,v = np.linalg.eig(cov_matrix)

    return np.sum(w)

<|endoftext|>


<commit_before>from xml.dom import minidom
from types import *
import datetime
import csv
import os
import re
import sqlite3
import copy
import unicodedata

class XMLPatent(object):
    """
    Base class for handling parsing of xml fields
    """

    def __init__(self, xmlstring):
        """
        [xmlstring]: string containing xml document. Should be provided by
        parse.py
        """
        # lowercase all tags
        self.xmlstring = re.sub(r"<[/]?[A-Za-z-]+?[ >]", lambda x: x.group().lower(), xmlstring)
        # store the minidom parsed xml doc
        self.xmldoc = minidom.parseString(self.xmlstring)

        # country, patent, kind, date_grant
        self.country, self.patent, self.kind, self.date_grant = self.__tagNme__(xmldoc, ["publication-reference", ["country", "doc-number", "kind", "date"]])
        # pat_type
        self.pat_type = self.__tagNme__(xmldoc, ["application-reference"], iHTML=False)[0].attributes["appl-type"].value
        # date_app, country_app, patent_app
        self.date_app, self.country_app, self.patent_app = self.__tagNme__(xmldoc, ["application-reference", ["date", "country", "doc-number"]])
        # code_app
        self.code_app = self.__tagNme__(xmldoc, ["us-application-series-code"])
        # clm_num
        self.clm_num = self.__tagNme__(xmldoc, ["number-of-claims"])
        # classes
        self.classes = [[x[:3].replace(' ',''), x[3:].replace(' ','')] for x in self.__tagNme__(xmldoc, ["classification-national", ["main-classification", "further-classification"]], idx=1, listType=True)]
        # abstract
        self.abstract = self.__allHTML__(xmldoc, ["abstract", "p"])
        # invention_title
        self.invention_title = self.__allHTML__(xmldoc, ["invention-title"])
        # asg_list
        self.asg_list = self.__asg_detail__(self.__tagNme__(xmldoc, ["assignees", "assignee"], iHTML=False))
        # cit_list
        self.cit_list = self.__cit_detail__(self.__tagNme__(xmldoc, ["references-cited", "citation"], iHTML=False))
        # rel_list
        self.rel_list = self.__rel_detail__(self.__tagNme__(xmldoc, ["us-related-documents"], iHTML=False))
        # inv_list
        self.inv_list = self.__tagSplit__(xmldoc, ["parties", "applicant"], [["addressbook", ["last-name", "first-name"]], ["addressbook", "address", ["street", "city", "state", "country", "postcode"]], [["nationality", "residence"], "country"]], blank=True)
        # law_list
        self.law_list = self.__tagSplit__(xmldoc, ["parties", "agents", "agent"], [["addressbook", ["last-name", "first-name", "country", "orgname"]]], blank=True)

        """
        Callback structure to handle the build_table specifics
        """
        self.tablecallbacks = {
            'assignee': self.build_assignee,
            'citation': self.build_citation,
            'class': self.build_class,
            'inventor': self.build_inventor,
            'patent': self.build_patent,
            'patdesc': self.build_patdesc,
            'lawyer': self.build_lawyer,
            'sciref': self.build_sciref,
            'usreldoc': self.build_usreldoc
            }

        """
        Callback structure for inserting patent into table
        """
        self.insertcallbacks = {
            'assignee': self.insert_assignee,
            'citation': self.insert_citation,
            'class': self.insert_class,
            'inventor': self.insert_inventor,
            'patent': self.insert_patent,
            'patdesc': self.insert_patdesc,
            'lawyer': self.insert_lawyer,
            'sciref': self.insert_sciref,
            'usreldoc': self.insert_usreldoc
        }

    def build_table(self, tablename):
        """
        Return list of requisite fields for inserting this patent into [tablename]
        """
        return self.tablecallbacks[tablename]()

    def build_assignee(self):
        ack = []
        for i,y in enumerate(self.asg_list):
            if not y[0]:
                ack.extend([[self, y[2], y[1], y[4], y[5], y[7], y[8], i]])
            else:
                ack.extend([[self, "00", "%s, %s" % (y[2], y[1]), y[4], y[5], y[6], y[7], y[8], i]])
        return ack

    def build_citation(self):
        ack = []
        for i,y in enumerate([x for x in self.cit_list if x[1] != ""]):
            ack.extend([[self, y[3], y[5], y[4], y[1], y[2], y[0], i]])
        return ack

    def build_class(self):
        ack = []
        for i,y in enumerate(self.classes):
            ack.extend([[self, (i==0)*1, y[0], y[1]]])
        return ack

    def build_inventor(self):
        ack = []
        for i,y in enumerate(self.inv_list):
            ack.extend([[self, y[1], y[0], y[2], y[3], y[4], y[5], y[6], y[8], i]])
        return ack

    def build_self(self):
        return [[self, self.kind, self.clm_num, self.code_app, self_app, self.date_grant, self.date_grant[:4], self.date_app, self.date_app[:4], self.pat_type]]

    def build_patdesc(self):
        return [[self, self.abstract, self.invention_title]]

    def build_lawyer(self):
        ack = []
        for i,y in enumerate(self.law_list):
            ack.extend([[self, y[1], y[0], y[2], y[3], i]])
        return ack

    def build_sciref(self):
        ack = []
        for i,y in enumerate([y for y in self.cit_list if y[1] == ""]):
            ack.extend([[self, y[-1], i]])
        return ack

    def build_usreldoc(self):
        ack = []
        for i,y in enumerate(self.rel_list):
            if y[1] == 1:
                ack.extend([[self, y[0], y[1], y[3], y[2], y[4], y[5], y[6]]])
            else:
                ack.extend([[self, y[0], y[1], y[3], y[2], y[4], "", ""]])
        return ack

    def insert_assignee(self):
        conn = sqlite3.connect("assignee.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS assignee (
                Patent VARCHAR(8),      AsgType INTEGER,        Assignee VARCHAR(30),
                City VARCHAR(10),       State VARCHAR(2),       Country VARCHAR(2),
                Nationality VARCHAR(2), Residence VARCHAR(2),   AsgSeq INTEGER);
            CREATE UNIQUE INDEX IF NOT EXISTS uqAsg ON assignee (Patent, AsgSeq);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["assignee"]())
        conn.commit()

    def insert_citation(self):
        conn = sqlite3.connect("citation.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS citation (
                Patent VARCHAR(8),      Cit_Date INTEGER,       Cit_Name VARCHAR(10),
                Cit_Kind VARCHAR(1),    Cit_Country VARCHAR(2), Citation VARCHAR(8),
                Category VARCHAR(15),   CitSeq INTEGER);
            CREATE UNIQUE INDEX IF NOT EXISTS uqCit ON citation (Patent, CitSeq);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?, ?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["citation"]())
        conn.commit()

    def insert_class(self):
        conn = sqlite3.connect("class.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS class (
                Patent VARCHAR(8),      Prim INTEGER,
                Class VARCHAR(3),       SubClass VARCHAR(3));
            CREATE UNIQUE INDEX IF NOT EXISTS uqClass ON class (Patent, Class, SubClass);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["class"]())
        conn.commit()

    def insert_inventor(self):
        conn = sqlite3.connect("inventor.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS inventor (
                Patent VARCHAR(8),      Firstname VARCHAR(15),  Lastname VARCHAR(15),
                Street VARCHAR(15),     City VARCHAR(10),
                State VARCHAR(2),       Country VARCHAR(12),
                Zipcode VARCHAR(5),     Nationality VARCHAR(2), InvSeq INTEGER);
            CREATE UNIQUE INDEX IF NOT EXISTS uqInv ON inventor (Patent, InvSeq);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["inventor"]())
        conn.commit()

    def insert_patent(self):
        conn = sqlite3.connect("patent.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS patent (
                Patent VARCHAR(8),      Kind VARCHAR(3),        Claims INTEGER,
                AppType INTEGER,        AppNum VARCHAR(8),
                GDate INTEGER,          GYear INTEGER,
                AppDate INTEGER,        AppYear INTEGER, PatType VARCHAR(15) );
            CREATE UNIQUE INDEX IF NOT EXISTS uqPat on patent (Patent);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["patent"]())
        conn.commit()

    def insert_patdesc(self):
        conn = sqlite3.connect("patdesc.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS patdesc (
                Patent VARCHAR(8),
                Abstract VARCHAR(50),   Title VARCHAR(20));
            CREATE UNIQUE INDEX IF NOT EXISTS uqPatDesc ON patdesc (Patent);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?)""" % tbl, \
            self.tablecallbacks["patdesc"]())
        conn.commit()

    def insert_lawyer(self):
        conn = sqlite3.connect("lawyer.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS lawyer (
                Patent VARCHAR(8),      Firstname VARCHAR(15),  Lastname VARCHAR(15),
                LawCountry VARCHAR(2),  OrgName VARCHAR(20),    LawSeq INTEGER);
            CREATE UNIQUE INDEX IF NOT EXISTS uqLawyer ON lawyer (Patent, LawSeq);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["lawyer"]())
        conn.commit()

    def insert_sciref(self):
        conn = sqlite3.connect("sciref.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS sciref (
                Patent VARCHAR(8),      Descrip VARCHAR(20),    CitSeq INTEGER);
            CREATE UNIQUE INDEX IF NOT EXISTS uqSciref ON sciref (Patent, CitSeq);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?)""" % tbl, \
            self.tablecallbacks["sciref"]())
        conn.commit()

    def insert_usreldoc(self):
        conn = sqlite3.connect("usreldoc.sqlite3")
        c = conn.cursor()
        c.executescript("""
            CREATE TABLE IF NOT EXISTS usreldoc (
                Patent VARCHAR(8),      DocType VARCHAR(10),    OrderSeq INTEGER,
                Country VARCHAR(2),     RelPatent VARCHAR(8),   Kind VARCHAR(2),
                RelDate INTEGER,        Status VARCHAR(10));
            CREATE UNIQUE INDEX IF NOT EXISTS uqUSRelDoc ON usreldoc (Patent, OrderSeq);
            """)
        c.executemany("""INSERT OR IGNORE INTO %s VALUES (?, ?, ?, ?, ?, ?, ?, ?)""" % tbl, \
            self.tablecallbacks["usreldoc"]())
        conn.commit()

    """
    These are all methods from the old XMLPatent class. I'm keeping them
    in here to assist in the carry-over of parsing the xml fields
    """
    def __allHTML__(self, xmldoc, tagList):
        """
        Replaces the html tags for everything returned by __tagName__(taglist)
        with nothing
        """
        for x in self.__tagNme__(xmldoc, tagList, iHTML=False):
            return re.sub(r"<[/]?%s( .*?)?>" % (tagList[-1]), "", x.toxml())
        return ""

    def __innerHTML__(self, dom_element):
        """
        Gets the text out of all child nodes for a certain
        dom_element
        """
        #if blank return nothing as well!
        if dom_element == '':
            return ''
        else:
            rc = ""
            for node in dom_element.childNodes:
                if node.nodeType == node.TEXT_NODE:
                    rc = rc + node.data
            return rc

    def __tagSplit__(self, xmldoc, xmlList, tagList, baseList=[], idx=0, blank=False, iHTML=True, debug=False):
        """
        For each item in the list of xml tags returned by tagName, we treat each tag's contents
        as its own xml doc and search it for a list of xml tags. Everyything is appended together
        and returned
        """
        d_list = []
        for x in self.__tagNme__(xmldoc, tagList=xmlList, iHTML=False):
            record = copy.copy(baseList)
            for y in tagList:
                if debug:
                    print "-------------------"
                    print x.toxml()
                    print y
                record.extend(self.__tagNme__(x, tagList=y, blank=blank, iHTML=iHTML, debug=debug, idx=idx))
            d_list.append(record)
        return d_list

    def __tagNme__(self, xmldoc, tagList, idx=0, listType=False, blank=False, iHTML=True, debug=False):
        """
        takes in the xml.minidom parsed xml document [xmldoc] and a list of tags [tagList]
        [tagList] may sometimes be a list of lists?
        We iterate the taglist, searching another level deeper into the xml doc with each
        iteration. In tagList, index 0 is the first level of the xmldoc, index 1 is the list
        of all tags we look for at the level right under all the tags we found at index 0,
        and so on.
        For each item, we then iterate through all xmldocs we passed in (usually one?)
        and append the tag we wanted to an xmllist.
        We have empty strings if the tag was not found, and always return a flat list.
        **Returns:
        if the iHTML flag is set, we do the innerHTML method on the xmllist, otherwise
        we just return the xmllist.
        """
        xmldoc = [xmldoc]
        for i,x in enumerate(tagList):
            if type(x) is not ListType:
                x = [x]
            xmlnext = []
            for y in x:
                for z in xmldoc:
                    if z != '':
                        if i==0 and idx!=0:
                            if len(z.getElementsByTagName(y))>0:
                                xmlnext.append(z.getElementsByTagName(y)[idx-1])
                            else:
                                xmlnext.append('')
                        else:
                            blFlag = False
                            for za in z.getElementsByTagName(y):
                                blFlag = True
                                xmlnext.append(za)
                            if blFlag==False and blank==True:
                                xmlnext.append('')
                    else:
                        xmlnext.append('')
            xmldoc = xmlnext

        if debug:
            if len(xmldoc)==1 and iHTML:
                print self.__innerHTML__(xmldoc[0])
            elif iHTML:
                print [self.__innerHTML__(x) for x in xmldoc]
            else:
                print xmldoc

        if len(xmldoc)==1 and iHTML:
            if listType:
                return [self.__innerHTML__(xmldoc[0])]
            else:
                return self.__innerHTML__(xmldoc[0])
        elif iHTML:
            return [self.__innerHTML__(x) for x in xmldoc]
        else:
            return xmldoc

    def __asg_detail__(self, xmldoc):
        d_list = []
        for x in xmldoc:
            record = []
            if len(x.getElementsByTagName("first-name"))>0:
                record = [1]
                record.extend(self.__tagNme__(x, [["last-name", "first-name"]]))
            else:
                record = [0]
                record.extend(self.__tagNme__(x, [["orgname", "role"]]))
            record.extend(self.__tagNme__(x, ["addressbook", "address", ["street", "city", "state", "country", "postcode"]], blank=True))
            record.extend(self.__tagNme__(x, [["nationality", "residence"], "country"], blank=True))
            d_list.append(record)
        return d_list

    def __cit_detail__(self, xmldoc):
        d_list = []
        for x in xmldoc:
            #this means patcit is part of the XML
            record = [self.__tagNme__(x, ["category"])]
            if len(x.getElementsByTagName("patcit"))>0:
                record.extend(self.__tagNme__(x, ["patcit", ["country", "doc-number", "date", "kind", "name"]], blank=True))
                record.extend([""])
            elif len(x.getElementsByTagName("othercit"))>0:
                record.extend(["", "", "", "", ""])
                record.extend([self.__allHTML__(x, ["othercit"])])
                #probably should grab date information
            else:
                print x.toxml()
            d_list.append(record)
        return d_list

    def __rel_detail__(self, xmldoc, debug=False):
        d_list = []
        for x in xmldoc:
            for y in ["continuation-in-part", "continuation", "division", "reissue"]:
                if len(x.getElementsByTagName(y))>0:
                    d_list.extend(self.__tagSplit__(x, ["relation", "child-doc"], [[["doc-number", "country", "kind"]]], baseList=[y, -1], blank=True))
                    d_list.extend(self.__tagSplit__(x, ["relation", "parent-doc"], [[["doc-number", "country", "kind", "date", "parent-status"]]], baseList=[y, 1], blank=True, idx=1))
                    d_list.extend(self.__tagSplit__(x, ["relation", "parent-doc", "parent-grant-document"], [[["doc-number", "country", "kind", "date", "parent-status"]]], baseList=[y, 1], blank=True))
                    d_list.extend(self.__tagSplit__(x, ["relation", "parent-doc", "parent-pct-document"],  [[["doc-number", "country", "kind", "date", "parent-status"]]], baseList=[y, 1], blank=True))
            for y in ["related-publication", "us-provisional-application"]:
                if len(x.getElementsByTagName(y))>0:
                    d_list.extend(self.__tagSplit__(x, ["document-id"], [[["doc-number", "country", "kind"]]], baseList=[y, 0], blank=True))
            if debug:
                print "-------------------"
                for x in d_list:
                    print x
        return d_list

    def __repr__(self):
        return \
"""country = %s, patent = %s, pat_type = %s,
date_grant = %s, date_app = %s,
         abstract = %s
  invention_title = %s
len(classes, asg, cit, ret, inv, law) = %s""" % (self.country, self.patent, self.pat_type, self.date_grant, self.date_app,
       self.abstract[:50], self.invention_title[:50],
       str([len(self.classes),  len(self.asg_list), len(self.cit_list),
            len(self.rel_list), len(self.inv_list), len(self.law_list)]))
<commit_msg>use new patXML file<commit_after><|endoftext|>


<commit_before>import warnings
import itertools

import numpy as np

from skimage import img_as_float
from skimage._shared import six
from skimage._shared.six.moves import zip
from .colorconv import rgb2gray, gray2rgb
from . import rgb_colors

__all__ = ['color_dict', 'label2rgb', 'DEFAULT_COLORS']

DEFAULT_COLORS = ('red', 'blue', 'yellow', 'magenta', 'green',
                  'indigo', 'darkorange', 'cyan', 'pink', 'yellowgreen')

color_dict = rgb_colors.__dict__

def _rgb_vector(color):
    """Return RGB color as (1, 3) array.

    This RGB array gets multiplied by masked regions of an RGB image, which are
    partially flattened by masking (i.e. dimensions 2D + RGB -> 1D + RGB).

    Parameters
    ----------
    color : str or array
        Color name in `color_dict` or RGB float values between [0, 1].
    """
    if isinstance(color, six.string_types):
        color = color_dict[color]
    # slice to handle RGBA colors
    return np.array(color[:3]).reshape(1, 3)

def label2rgb(label, image=None, colors=None, alpha=0.3,
              bg_label=-1, bg_color=None, image_alpha=1):
    """Return an RGB image where color-coded labels are painted over the image.

    Parameters
    ----------
    label : array
        Integer array of labels with the same shape as `image`.
    image : array
        Image used as underlay for labels. If the input is an RGB image, it's
        converted to grayscale before coloring.
    colors : list
        List of colors. If the number of labels exceeds the number of colors,
        then the colors are cycled.
    alpha : float [0, 1]
        Opacity of colorized labels. Ignored if image is `None`.
    bg_label : int
        Label that's treated as the background.
    bg_color : str or array
        Background color. Must be a name in `color_dict` or RGB float values
        between [0, 1].
    image_alpha : float [0, 1]
        Opacity of the image.
    """
    if colors is None:
        colors = DEFAULT_COLORS
    colors = [_rgb_vector(c) for c in colors]

    if image is None:
        img_layer = np.zeros(label.shape + (3,), dtype=np.float64)
        # Opacity doesn't make sense if no image exists.
        alpha = 1
    else:
        if not image.shape[:2] == label.shape:
            raise ValueError("`image` and `label` must be the same shape")

        if image.min() < 0:
            warnings.warn("Negative intensities in `image` are not supported")

        image = img_as_float(rgb2gray(image))
        img_layer = gray2rgb(image) * image_alpha + (1 - image_alpha)

    # need to ensure that all labels are ints >= 0
    offset = label.min()
    if offset != 0:
        label -= offset
        bg_label -= offset
    new_type = np.min_scalar_type(label.max())
    if new_type == np.bool:
        new_type = np.uint8
    label = label.astype(new_type)

    labels = list(set(label.flat))
    color_cycle = itertools.cycle(colors)

    remove_background = bg_label in labels and bg_color is None

    if bg_label in labels:
        labels.remove(bg_label)
        if bg_color is not None:
            labels.insert(0, bg_label)
            bg_color = _rgb_vector(bg_color)
            color_cycle = itertools.chain(bg_color, color_cycle)

    label_to_color = np.zeros((max(labels) + 1, 3))
    for lab, c in zip(labels, color_cycle):
        label_to_color[lab] = c

    label_layer = label_to_color[label]
    result = label_layer * alpha + img_layer * (1 - alpha)

    # remove background label if its color was not specified
    if remove_background:
        result[label == bg_label] = img_layer[label == bg_label]

    return result
<commit_msg>handle case when there are no labels<commit_after>import warnings
import itertools

import numpy as np

from skimage import img_as_float
from skimage._shared import six
from skimage._shared.six.moves import zip
from .colorconv import rgb2gray, gray2rgb
from . import rgb_colors

__all__ = ['color_dict', 'label2rgb', 'DEFAULT_COLORS']

DEFAULT_COLORS = ('red', 'blue', 'yellow', 'magenta', 'green',
                  'indigo', 'darkorange', 'cyan', 'pink', 'yellowgreen')

color_dict = rgb_colors.__dict__

def _rgb_vector(color):
    """Return RGB color as (1, 3) array.

    This RGB array gets multiplied by masked regions of an RGB image, which are
    partially flattened by masking (i.e. dimensions 2D + RGB -> 1D + RGB).

    Parameters
    ----------
    color : str or array
        Color name in `color_dict` or RGB float values between [0, 1].
    """
    if isinstance(color, six.string_types):
        color = color_dict[color]
    # slice to handle RGBA colors
    return np.array(color[:3]).reshape(1, 3)

def label2rgb(label, image=None, colors=None, alpha=0.3,
              bg_label=-1, bg_color=None, image_alpha=1):
    """Return an RGB image where color-coded labels are painted over the image.

    Parameters
    ----------
    label : array
        Integer array of labels with the same shape as `image`.
    image : array
        Image used as underlay for labels. If the input is an RGB image, it's
        converted to grayscale before coloring.
    colors : list
        List of colors. If the number of labels exceeds the number of colors,
        then the colors are cycled.
    alpha : float [0, 1]
        Opacity of colorized labels. Ignored if image is `None`.
    bg_label : int
        Label that's treated as the background.
    bg_color : str or array
        Background color. Must be a name in `color_dict` or RGB float values
        between [0, 1].
    image_alpha : float [0, 1]
        Opacity of the image.
    """
    if colors is None:
        colors = DEFAULT_COLORS
    colors = [_rgb_vector(c) for c in colors]

    if image is None:
        img_layer = np.zeros(label.shape + (3,), dtype=np.float64)
        # Opacity doesn't make sense if no image exists.
        alpha = 1
    else:
        if not image.shape[:2] == label.shape:
            raise ValueError("`image` and `label` must be the same shape")

        if image.min() < 0:
            warnings.warn("Negative intensities in `image` are not supported")

        image = img_as_float(rgb2gray(image))
        img_layer = gray2rgb(image) * image_alpha + (1 - image_alpha)

    # need to ensure that all labels are ints >= 0
    offset = label.min()
    if offset != 0:
        label -= offset
        bg_label -= offset
    new_type = np.min_scalar_type(label.max())
    if new_type == np.bool:
        new_type = np.uint8
    label = label.astype(new_type)

    labels = list(set(label.flat))
    color_cycle = itertools.cycle(colors)

    remove_background = bg_label in labels and bg_color is None

    if bg_label in labels:
        labels.remove(bg_label)
        if bg_color is not None:
            labels.insert(0, bg_label)
            bg_color = _rgb_vector(bg_color)
            color_cycle = itertools.chain(bg_color, color_cycle)

    if len(labels) == 0:
        return img_layer

    label_to_color = np.zeros((max(labels) + 1, 3))
    for lab, c in zip(labels, color_cycle):
        label_to_color[lab] = c

    label_layer = label_to_color[label]
    result = label_layer * alpha + img_layer * (1 - alpha)

    # remove background label if its color was not specified
    if remove_background:
        result[label == bg_label] = img_layer[label == bg_label]

    return result
<|endoftext|>


<commit_before>import numpy as np
from ._geometric import (warp, SimilarityTransform, AffineTransform,
                         ProjectiveTransform)

def resize(image, output_shape, order=1, mode='constant', cval=0.):
    """Resize image.

    Parameters
    ----------
    image : ndarray
        Input image.
    output_shape : tuple or ndarray
        Size of the generated output image `(rows, cols)`.

    Returns
    -------
    resized : ndarray
        Resized version of the input.

    Other parameters
    ----------------
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    rows, cols = output_shape
    orig_rows, orig_cols = image.shape[0], image.shape[1]

    row_scale = float(orig_rows) / rows
    col_scale = float(orig_cols) / cols

    # 3 control points necessary to estimate exact AffineTransform
    src_corners = np.array([[1, 1], [1, rows], [cols, rows]]) - 1
    dst_corners = np.zeros(src_corners.shape, dtype=np.double)
    # take into account that 0th pixel is at position (0.5, 0.5)
    dst_corners[:, 0] = col_scale * (src_corners[:, 0] + 0.5) - 0.5
    dst_corners[:, 1] = row_scale * (src_corners[:, 1] + 0.5) - 0.5

    tform = AffineTransform()
    tform.estimate(src_corners, dst_corners)

    return warp(image, tform, output_shape=output_shape, order=order,
                mode=mode, cval=cval)

def rescale(image, scale, order=1, mode='constant', cval=0.):
    """Scale image.

    Parameters
    ----------
    image : ndarray
        Input image.
    scale : {float, tuple of floats}
        Scale factors. Separate scale factors can be defined as
        `(row_scale, col_scale)`.

    Returns
    -------
    scaled : ndarray
        Scaled version of the input.

    Other parameters
    ----------------
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    try:
        row_scale, col_scale = scale
    except TypeError:
        row_scale = col_scale = scale

    orig_rows, orig_cols = image.shape[0], image.shape[1]
    rows = np.round(row_scale * orig_rows)
    cols = np.round(col_scale * orig_cols)
    output_shape = (rows, cols)

    return resize(image, output_shape, order=order, mode=mode, cval=cval)

def rotate(image, angle, resize=False, order=1, mode='constant', cval=0.):
    """Rotate image by a certain angle around its center.

    Parameters
    ----------
    image : ndarray
        Input image.
    angle : float
        Rotation angle in degrees in counter-clockwise direction.
    resize: bool, optional
        Determine whether the shape of the output image will be automatically
        calculated, so the complete rotated image exactly fits. Default is
        False.

    Returns
    -------
    rotated : ndarray
        Rotated version of the input.

    Other parameters
    ----------------
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    rows, cols = image.shape[0], image.shape[1]

    # rotation around center
    translation = np.array((cols, rows)) / 2. - 0.5
    tform1 = SimilarityTransform(translation=-translation)
    tform2 = SimilarityTransform(rotation=np.deg2rad(angle))
    tform3 = SimilarityTransform(translation=translation)
    tform = tform1 + tform2 + tform3

    output_shape = None
    if not resize:
        # determine shape of output image
        corners = np.array([[1, 1], [1, rows], [cols, rows], [cols, 1]])
        corners = tform(corners - 1)
        minc = corners[:, 0].min()
        minr = corners[:, 1].min()
        maxc = corners[:, 0].max()
        maxr = corners[:, 1].max()
        out_rows = maxr - minr + 1
        out_cols = maxc - minc + 1
        output_shape = np.ceil((out_rows, out_cols))

        # fit output image in new shape
        translation = ((cols - out_cols) / 2., (rows - out_rows) / 2.)
        tform4 = SimilarityTransform(translation=translation)
        tform = tform4 + tform

    return warp(image, tform, output_shape=output_shape, order=order,
                mode=mode, cval=cval)

def _swirl_mapping(xy, center, rotation, strength, radius):
    x, y = xy.T
    x0, y0 = center
    rho = np.sqrt((x - x0) ** 2 + (y - y0) ** 2)

    # Ensure that the transformation decays to approximately 1/1000-th
    # within the specified radius.
    radius = radius / 5 * np.log(2)

    theta = rotation + strength * \
            np.exp(-rho / radius) + \
            np.arctan2(y - y0, x - x0)

    xy[..., 0] = x0 + rho * np.cos(theta)
    xy[..., 1] = y0 + rho * np.sin(theta)

    return xy

def swirl(image, center=None, strength=1, radius=100, rotation=0,
          output_shape=None, order=1, mode='constant', cval=0):
    """Perform a swirl transformation.

    Parameters
    ----------
    image : ndarray
        Input image.
    center : (x,y) tuple or (2,) ndarray
        Center coordinate of transformation.
    strength : float
        The amount of swirling applied.
    radius : float
        The extent of the swirl in pixels.  The effect dies out
        rapidly beyond `radius`.
    rotation : float
        Additional rotation applied to the image.

    Returns
    -------
    swirled : ndarray
        Swirled version of the input.

    Other parameters
    ----------------
    output_shape : tuple or ndarray
        Size of the generated output image.
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    if center is None:
        center = np.array(image.shape)[:2] / 2

    warp_args = {'center': center,
                 'rotation': rotation,
                 'strength': strength,
                 'radius': radius}

    return warp(image, _swirl_mapping, map_args=warp_args,
                output_shape=output_shape,
                order=order, mode=mode, cval=cval)

def homography(image, H, output_shape=None, order=1,
               mode='constant', cval=0.):
    """
    .. note:: Deprecated in skimage 0.7
        `homography` will be removed in skimage 0.8, it is replaced by
        `warp` because the latter provides the same functionality::

            warp(image, ProjectiveTransform(H))

    Perform a projective transformation (homography) on an image.

    For each pixel, given its homogeneous coordinate :math:`\mathbf{x}
    = [x, y, 1]^T`, its target position is calculated by multiplying
    with the given matrix, :math:`H`, to give :math:`H \mathbf{x}`.
    E.g., to rotate by theta degrees clockwise, the matrix should be

    ::

      [[cos(theta) -sin(theta) 0]
       [sin(theta)  cos(theta) 0]
       [0            0         1]]

    or, to translate x by 10 and y by 20,

    ::

      [[1 0 10]
       [0 1 20]
       [0 0 1 ]].

    Parameters
    ----------
    image : 2-D array
        Input image.
    H : array of shape ``(3, 3)``
        Transformation matrix H that defines the homography.
    output_shape : tuple (rows, cols)
        Shape of the output image generated.
    order : int
        Order of splines used in interpolation.
    mode : string
        How to handle values outside the image borders.  Passed as-is
        to ndimage.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    Examples
    --------
    >>> # rotate by 90 degrees around origin and shift down by 2
    >>> x = np.arange(9, dtype=np.uint8).reshape((3, 3)) + 1
    >>> x
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]], dtype=uint8)
    >>> theta = -np.pi/2
    >>> M = np.array([[np.cos(theta),-np.sin(theta),0],
    ...               [np.sin(theta), np.cos(theta),2],
    ...               [0,             0,            1]])
    >>> x90 = homography(x, M, order=1)
    >>> x90
    array([[3, 6, 9],
           [2, 5, 8],
           [1, 4, 7]], dtype=uint8)
    >>> # translate right by 2 and down by 1
    >>> y = np.zeros((5,5), dtype=np.uint8)
    >>> y[1, 1] = 255
    >>> y
    array([[  0,   0,   0,   0,   0],
           [  0, 255,   0,   0,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0]], dtype=uint8)
    >>> M = np.array([[ 1.,  0.,  2.],
    ...               [ 0.,  1.,  1.],
    ...               [ 0.,  0.,  1.]])
    >>> y21 = homography(y, M, order=1)
    >>> y21
    array([[  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0, 255,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0]], dtype=uint8)

    """
    import warnings
    warnings.warn('the homography function is deprecated; '
                  'use the `warp` and `ProjectiveTransform` class instead',
                  category=DeprecationWarning)

    tform = ProjectiveTransform(H)
    return warp(image, inverse_map=tform.inverse, output_shape=output_shape,
                order=order, mode=mode, cval=cval)
<commit_msg>Enhance short description of resize and rescale functions<commit_after>import numpy as np
from ._geometric import (warp, SimilarityTransform, AffineTransform,
                         ProjectiveTransform)

def resize(image, output_shape, order=1, mode='constant', cval=0.):
    """Resize image to match a certain size.

    Parameters
    ----------
    image : ndarray
        Input image.
    output_shape : tuple or ndarray
        Size of the generated output image `(rows, cols)`.

    Returns
    -------
    resized : ndarray
        Resized version of the input.

    Other parameters
    ----------------
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    rows, cols = output_shape
    orig_rows, orig_cols = image.shape[0], image.shape[1]

    row_scale = float(orig_rows) / rows
    col_scale = float(orig_cols) / cols

    # 3 control points necessary to estimate exact AffineTransform
    src_corners = np.array([[1, 1], [1, rows], [cols, rows]]) - 1
    dst_corners = np.zeros(src_corners.shape, dtype=np.double)
    # take into account that 0th pixel is at position (0.5, 0.5)
    dst_corners[:, 0] = col_scale * (src_corners[:, 0] + 0.5) - 0.5
    dst_corners[:, 1] = row_scale * (src_corners[:, 1] + 0.5) - 0.5

    tform = AffineTransform()
    tform.estimate(src_corners, dst_corners)

    return warp(image, tform, output_shape=output_shape, order=order,
                mode=mode, cval=cval)

def rescale(image, scale, order=1, mode='constant', cval=0.):
    """Scale image by a certain factor.

    Parameters
    ----------
    image : ndarray
        Input image.
    scale : {float, tuple of floats}
        Scale factors. Separate scale factors can be defined as
        `(row_scale, col_scale)`.

    Returns
    -------
    scaled : ndarray
        Scaled version of the input.

    Other parameters
    ----------------
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    try:
        row_scale, col_scale = scale
    except TypeError:
        row_scale = col_scale = scale

    orig_rows, orig_cols = image.shape[0], image.shape[1]
    rows = np.round(row_scale * orig_rows)
    cols = np.round(col_scale * orig_cols)
    output_shape = (rows, cols)

    return resize(image, output_shape, order=order, mode=mode, cval=cval)

def rotate(image, angle, resize=False, order=1, mode='constant', cval=0.):
    """Rotate image by a certain angle around its center.

    Parameters
    ----------
    image : ndarray
        Input image.
    angle : float
        Rotation angle in degrees in counter-clockwise direction.
    resize: bool, optional
        Determine whether the shape of the output image will be automatically
        calculated, so the complete rotated image exactly fits. Default is
        False.

    Returns
    -------
    rotated : ndarray
        Rotated version of the input.

    Other parameters
    ----------------
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    rows, cols = image.shape[0], image.shape[1]

    # rotation around center
    translation = np.array((cols, rows)) / 2. - 0.5
    tform1 = SimilarityTransform(translation=-translation)
    tform2 = SimilarityTransform(rotation=np.deg2rad(angle))
    tform3 = SimilarityTransform(translation=translation)
    tform = tform1 + tform2 + tform3

    output_shape = None
    if not resize:
        # determine shape of output image
        corners = np.array([[1, 1], [1, rows], [cols, rows], [cols, 1]])
        corners = tform(corners - 1)
        minc = corners[:, 0].min()
        minr = corners[:, 1].min()
        maxc = corners[:, 0].max()
        maxr = corners[:, 1].max()
        out_rows = maxr - minr + 1
        out_cols = maxc - minc + 1
        output_shape = np.ceil((out_rows, out_cols))

        # fit output image in new shape
        translation = ((cols - out_cols) / 2., (rows - out_rows) / 2.)
        tform4 = SimilarityTransform(translation=translation)
        tform = tform4 + tform

    return warp(image, tform, output_shape=output_shape, order=order,
                mode=mode, cval=cval)

def _swirl_mapping(xy, center, rotation, strength, radius):
    x, y = xy.T
    x0, y0 = center
    rho = np.sqrt((x - x0) ** 2 + (y - y0) ** 2)

    # Ensure that the transformation decays to approximately 1/1000-th
    # within the specified radius.
    radius = radius / 5 * np.log(2)

    theta = rotation + strength * \
            np.exp(-rho / radius) + \
            np.arctan2(y - y0, x - x0)

    xy[..., 0] = x0 + rho * np.cos(theta)
    xy[..., 1] = y0 + rho * np.sin(theta)

    return xy

def swirl(image, center=None, strength=1, radius=100, rotation=0,
          output_shape=None, order=1, mode='constant', cval=0):
    """Perform a swirl transformation.

    Parameters
    ----------
    image : ndarray
        Input image.
    center : (x,y) tuple or (2,) ndarray
        Center coordinate of transformation.
    strength : float
        The amount of swirling applied.
    radius : float
        The extent of the swirl in pixels.  The effect dies out
        rapidly beyond `radius`.
    rotation : float
        Additional rotation applied to the image.

    Returns
    -------
    swirled : ndarray
        Swirled version of the input.

    Other parameters
    ----------------
    output_shape : tuple or ndarray
        Size of the generated output image.
    order : int
        Order of splines used in interpolation.  See
        `scipy.ndimage.map_coordinates` for detail.
    mode : string
        How to handle values outside the image borders.  See
        `scipy.ndimage.map_coordinates` for detail.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    """

    if center is None:
        center = np.array(image.shape)[:2] / 2

    warp_args = {'center': center,
                 'rotation': rotation,
                 'strength': strength,
                 'radius': radius}

    return warp(image, _swirl_mapping, map_args=warp_args,
                output_shape=output_shape,
                order=order, mode=mode, cval=cval)

def homography(image, H, output_shape=None, order=1,
               mode='constant', cval=0.):
    """
    .. note:: Deprecated in skimage 0.7
        `homography` will be removed in skimage 0.8, it is replaced by
        `warp` because the latter provides the same functionality::

            warp(image, ProjectiveTransform(H))

    Perform a projective transformation (homography) on an image.

    For each pixel, given its homogeneous coordinate :math:`\mathbf{x}
    = [x, y, 1]^T`, its target position is calculated by multiplying
    with the given matrix, :math:`H`, to give :math:`H \mathbf{x}`.
    E.g., to rotate by theta degrees clockwise, the matrix should be

    ::

      [[cos(theta) -sin(theta) 0]
       [sin(theta)  cos(theta) 0]
       [0            0         1]]

    or, to translate x by 10 and y by 20,

    ::

      [[1 0 10]
       [0 1 20]
       [0 0 1 ]].

    Parameters
    ----------
    image : 2-D array
        Input image.
    H : array of shape ``(3, 3)``
        Transformation matrix H that defines the homography.
    output_shape : tuple (rows, cols)
        Shape of the output image generated.
    order : int
        Order of splines used in interpolation.
    mode : string
        How to handle values outside the image borders.  Passed as-is
        to ndimage.
    cval : string
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    Examples
    --------
    >>> # rotate by 90 degrees around origin and shift down by 2
    >>> x = np.arange(9, dtype=np.uint8).reshape((3, 3)) + 1
    >>> x
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]], dtype=uint8)
    >>> theta = -np.pi/2
    >>> M = np.array([[np.cos(theta),-np.sin(theta),0],
    ...               [np.sin(theta), np.cos(theta),2],
    ...               [0,             0,            1]])
    >>> x90 = homography(x, M, order=1)
    >>> x90
    array([[3, 6, 9],
           [2, 5, 8],
           [1, 4, 7]], dtype=uint8)
    >>> # translate right by 2 and down by 1
    >>> y = np.zeros((5,5), dtype=np.uint8)
    >>> y[1, 1] = 255
    >>> y
    array([[  0,   0,   0,   0,   0],
           [  0, 255,   0,   0,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0]], dtype=uint8)
    >>> M = np.array([[ 1.,  0.,  2.],
    ...               [ 0.,  1.,  1.],
    ...               [ 0.,  0.,  1.]])
    >>> y21 = homography(y, M, order=1)
    >>> y21
    array([[  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0, 255,   0],
           [  0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0]], dtype=uint8)

    """
    import warnings
    warnings.warn('the homography function is deprecated; '
                  'use the `warp` and `ProjectiveTransform` class instead',
                  category=DeprecationWarning)

    tform = ProjectiveTransform(H)
    return warp(image, inverse_map=tform.inverse, output_shape=output_shape,
                order=order, mode=mode, cval=cval)
<|endoftext|>