Ejemplo n.º 1
0
    def InitVariables(self):
        """!Initialize any variables nneded by application"""
        self.currentRaster = None
        self.statitistics = dict()

        # use WIND_OVERRIDE region not to affect current region
        gcore.use_temp_region()
def main():
    options, flags = gcore.parser()
    probability = options['probability']
    output = options['output']
    count = int(options['count'])

    gcore.use_temp_region()

    # probability map
    probab_01 = 'probability_01_' + str(os.getpid())
    TMP_RAST.append(probab_01)
    info = grast.raster_info(probability)
    gcore.write_command('r.recode', flags='d', input=probability, output=probab_01,
                        title="Recoded probability map to 0 to 1",
                        rules='-', stdin='{minim}:{maxim}:0:1'.format(minim=info['min'], maxim=info['max']))
    mean = gcore.parse_key_val(gcore.read_command('r.univar', map=probab_01, flags='g'),
                               val_type=float)['mean']
    resolution = count / (mean * (info['north'] - info['south'] + info['east'] - info['west']))
    resolution = sqrt((mean * (info['north'] - info['south']) * (info['east'] - info['west'])) / count)
    gcore.run_command('g.region', res=resolution)

    random_name = 'random_' + str(os.getpid())
    point_map = 'points_' + str(os.getpid())
    point_grid = 'points_' + str(os.getpid())
    TMP_RAST.append(random_name)
    TMP_RAST.append(point_map)
    TMP_VECT.append(point_grid)

    gcore.run_command('r.surf.random', output=random_name, min=0, max=1)
    grast.mapcalc(exp='{point_map} = if({rand} <= {prob}, 1, null())'.format(rand=random_name,
                                                                             prob=probab_01,
                                                                             point_map=point_map))
    gcore.run_command('r.to.vect', flags='t', input=point_map, output=point_grid, type='point')
    gcore.run_command('v.perturb', input=point_grid, output=output,
                      parameter=resolution / 2., seed=os.getpid())
Ejemplo n.º 3
0
    def InitVariables(self):
        """!Initialize any variables nneded by application"""
        self.currentRaster = None
        self.statitistics = dict()

        # use WIND_OVERRIDE region not to affect current region
        gcore.use_temp_region()
Ejemplo n.º 4
0
 def writeCircle(self, circle, rasterName):
     coords = self.mapWindow.Pixel2Cell(circle.point)
     RunCommand('r.circle', output=rasterName, max=circle.radius,
                coordinate=coords, flags="b")
     grass.use_temp_region()
     grass.run_command('g.region', zoom=rasterName)
     region = grass.region()
     marea = MaskedArea(region, rasterName, circle.radius)
     return marea
Ejemplo n.º 5
0
 def writeCircle(self, circle, rasterName):
     coords = self.mapWindow.Pixel2Cell(circle.point)
     RunCommand('r.circle', output=rasterName, max=circle.radius,
                coordinate=coords, flags="b")
     grass.use_temp_region()
     grass.run_command('g.region', zoom=rasterName)
     region = grass.region()
     marea = MaskedArea(region, rasterName, circle.radius)
     return marea
Ejemplo n.º 6
0
    def writeArea(self, coords, rasterName):
        polyfile = tempfile.NamedTemporaryFile(delete=False)
        polyfile.write("AREA\n")
        for coor in coords:
            east, north = coor
            point = " %s %s\n" % (east, north)
            polyfile.write(point)

        catbuf = "=%d a\n" % self.catId
        polyfile.write(catbuf)
        self.catId = self.catId + 1

        polyfile.close()
        region_settings = grass.parse_command("g.region",
                                              flags="p",
                                              delimiter=":")
        pname = polyfile.name.split("/")[-1]
        tmpraster = "rast_" + pname
        tmpvector = "vect_" + pname
        wx.BeginBusyCursor()
        wx.GetApp().Yield()
        RunCommand(
            "r.in.poly",
            input=polyfile.name,
            output=tmpraster,
            rows=region_settings["rows"],
            overwrite=True,
        )

        RunCommand("r.to.vect",
                   input=tmpraster,
                   output=tmpvector,
                   type="area",
                   overwrite=True)

        RunCommand("v.to.rast",
                   input=tmpvector,
                   output=rasterName,
                   value=1,
                   use="val")
        wx.EndBusyCursor()
        grass.use_temp_region()
        grass.run_command("g.region", vector=tmpvector)
        region = grass.region()

        marea = MaskedArea(region, rasterName)

        RunCommand("g.remove", flags="f", type="raster", name=tmpraster)
        RunCommand("g.remove", flags="f", type="vector", name=tmpvector)

        os.unlink(polyfile.name)
        return marea
Ejemplo n.º 7
0
    def writeArea(self, coords, rasterName):
        polyfile = tempfile.NamedTemporaryFile(delete=False)
        polyfile.write("AREA\n")
        for coor in coords:
            east, north = coor
            point = " %s %s\n" % (east, north)
            polyfile.write(point)

        catbuf = "=%d a\n" % self.catId
        polyfile.write(catbuf)
        self.catId = self.catId + 1

        polyfile.close()
        region_settings = grass.parse_command('g.region',
                                              flags='p',
                                              delimiter=':')
        pname = polyfile.name.split('/')[-1]
        tmpraster = "rast_" + pname
        tmpvector = "vect_" + pname
        wx.BeginBusyCursor()
        wx.Yield()
        RunCommand('r.in.poly',
                   input=polyfile.name,
                   output=tmpraster,
                   rows=region_settings['rows'],
                   overwrite=True)

        RunCommand('r.to.vect',
                   input=tmpraster,
                   output=tmpvector,
                   type='area',
                   overwrite=True)

        RunCommand('v.to.rast',
                   input=tmpvector,
                   output=rasterName,
                   value=1,
                   use='val')
        wx.EndBusyCursor()
        grass.use_temp_region()
        grass.run_command('g.region', vector=tmpvector)
        region = grass.region()

        marea = MaskedArea(region, rasterName)

        RunCommand('g.remove', flags='f', type='raster', name=tmpraster)
        RunCommand('g.remove', flags='f', type='vector', name=tmpvector)

        os.unlink(polyfile.name)
        return marea
Ejemplo n.º 8
0
    def _rectangleDrawn(self):
        """When drawing finished, get region values"""
        mouse = self.mapWindow.mouse
        item = self._registeredGraphics.GetItem(0)
        p1 = self.mapWindow.Pixel2Cell(mouse["begin"])
        p2 = self.mapWindow.Pixel2Cell(mouse["end"])
        item.SetCoords([p1, p2])
        region = {
            "n": max(p1[1], p2[1]),
            "s": min(p1[1], p2[1]),
            "w": min(p1[0], p2[0]),
            "e": max(p1[0], p2[0]),
        }
        item.SetPropertyVal("hide", False)
        self.mapWindow.ClearLines()
        self._registeredGraphics.Draw()
        if self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
            dlg = wx.MessageDialog(
                self,
                "Is this area ok?",
                "select sampling unit",
                wx.YES_NO | wx.ICON_QUESTION,
            )
            ret = dlg.ShowModal()
            if ret == wx.ID_YES:
                grass.use_temp_region()
                grass.run_command(
                    "g.region",
                    n=region["n"],
                    s=region["s"],
                    e=region["e"],
                    w=region["w"],
                )
                tregion = grass.region()
                self.sampleFrameChanged.emit(region=tregion)
                self.mapWindow.ClearLines()
                item = self._registeredGraphics.GetItem(0)
                item.SetPropertyVal("hide", True)
                layers = self.map_.GetListOfLayers()
                self.mapWindow.ZoomToMap(layers=layers,
                                         ignoreNulls=False,
                                         render=True)
            else:
                self.nextRegion(next=False)
            dlg.Destroy()

        elif self.samplingtype != SamplingType.WHOLE:
            """When drawing finished, get region values"""
            self.sampleFrameChanged.emit(region=region)
Ejemplo n.º 9
0
def run_modules_in_temp_region(module_list, q):
    """Run the modules in a temporary region environment

    This function is the argument for multiprocessing.Process class
    in the MultiModule asynchronous execution.

    :param module_list: The list of modules to run in serial
    :param q: The process queue to put the finished process list
    """
    use_temp_region()
    try:
        for proc in module_list:
            proc.run()
            proc.wait()
    finally:
        q.put(module_list)
        del_temp_region()
Ejemplo n.º 10
0
def run_modules_in_temp_region(module_list, q):
    """Run the modules in a temporary region environment

    This function is the argument for multiprocessing.Process class
    in the MultiModule asynchronous execution.

    :param module_list: The list of modules to run in serial
    :param q: The process queue to put the finished process list
    """
    use_temp_region()
    try:
        for proc in module_list:
            proc.run()
            proc.wait()
    except:
        raise
    finally:
        q.put(module_list)
        del_temp_region()
Ejemplo n.º 11
0
    def writeArea(self, coords, rasterName):
        polyfile = tempfile.NamedTemporaryFile(delete=False)
        polyfile.write("AREA\n")
        for coor in coords:
            east, north = coor
            point = " %s %s\n" % (east, north)
            polyfile.write(point)

        catbuf = "=%d a\n" % self.catId
        polyfile.write(catbuf)
        self.catId = self.catId + 1

        polyfile.close()
        region_settings = grass.parse_command('g.region', flags='p',
                                              delimiter=':')
        pname = polyfile.name.split('/')[-1]
        tmpraster = "rast_" + pname
        tmpvector = "vect_" + pname
        wx.BeginBusyCursor()
        wx.Yield()
        RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
                   rows=region_settings['rows'], overwrite=True)

        RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
                   type='area', overwrite=True)

        RunCommand('v.to.rast', input=tmpvector, output=rasterName,
                   value=1, use='val')
        wx.EndBusyCursor()
        grass.use_temp_region()
        grass.run_command('g.region', vector=tmpvector)
        region = grass.region()

        marea = MaskedArea(region, rasterName)

        RunCommand('g.remove', flags='f', type='raster', name=tmpraster)
        RunCommand('g.remove', flags='f', type='vector', name=tmpvector)

        os.unlink(polyfile.name)
        return marea
Ejemplo n.º 12
0
    def _rectangleDrawn(self):
        """When drawing finished, get region values"""
        mouse = self.mapWindow.mouse
        item = self._registeredGraphics.GetItem(0)
        p1 = self.mapWindow.Pixel2Cell(mouse['begin'])
        p2 = self.mapWindow.Pixel2Cell(mouse['end'])
        item.SetCoords([p1, p2])
        region = {'n': max(p1[1], p2[1]),
                  's': min(p1[1], p2[1]),
                  'w': min(p1[0], p2[0]),
                  'e': max(p1[0], p2[0])}
        item.SetPropertyVal('hide', False)
        self.mapWindow.ClearLines()
        self._registeredGraphics.Draw(self.mapWindow.pdcTmp)
        if self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
            dlg = wx.MessageDialog(self, "Is this area ok?",
                                   "select sampling unit",
                                   wx.YES_NO | wx.ICON_QUESTION)
            ret = dlg.ShowModal()
            if ret == wx.ID_YES:
                grass.use_temp_region()
                grass.run_command('g.region', n=region['n'], s=region['s'],
                                  e=region['e'], w=region['w'])
                tregion = grass.region()
                self.sampleFrameChanged.emit(region=tregion)
                self.mapWindow.ClearLines()
                item = self._registeredGraphics.GetItem(0)
                item.SetPropertyVal('hide', True)
                layers = self.map_.GetListOfLayers()
                self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False,
                                         render=True)
            else:
                self.nextRegion(next=False)
            dlg.Destroy()

        elif self.samplingtype != SamplingType.WHOLE:
            """When drawing finished, get region values"""
            self.sampleFrameChanged.emit(region=region)
Ejemplo n.º 13
0
def main():
    size = int(options["size"])
    gamma = scale = None
    if options["gamma"]:
        gamma = float(options["gamma"])
    if options["scaling_factor"]:
        scale = float(options["scaling_factor"])
    input_dev = options["input"]
    output = options["output"]
    method = options["method"]

    if method in ("gravity", "kernel") and (gamma is None or scale is None):
        gcore.fatal(
            _("Methods gravity and kernel require options scaling_factor and gamma"
              ))

    temp_map = "tmp_futures_devPressure_" + str(os.getpid()) + "_copy"
    temp_map_out = "tmp_futures_devPressure_" + str(os.getpid()) + "_out"
    temp_map_nulls = "tmp_futures_devPressure_" + str(os.getpid()) + "_nulls"
    global TMP, TMPFILE
    if flags["n"]:
        gcore.message(_("Preparing data..."))
        region = gcore.region()
        gcore.use_temp_region()
        gcore.run_command(
            "g.region",
            n=region["n"] + size * region["nsres"],
            s=region["s"] - size * region["nsres"],
            e=region["e"] + size * region["ewres"],
            w=region["w"] - size * region["ewres"],
        )
        TMP.append(temp_map)
        TMP.append(temp_map_nulls)
        TMP.append(temp_map_out)
        exp = "{temp_map_nulls} = if(isnull({inp}), 1, null())".format(
            temp_map_nulls=temp_map_nulls, inp=input_dev)
        grast.mapcalc(exp=exp)
        grast.mapcalc(exp="{temp} = if(isnull({inp}), 0, {inp})".format(
            temp=temp_map, inp=input_dev))
        rmfilter_inp = temp_map
        rmfilter_out = temp_map_out
    else:
        rmfilter_inp = input_dev
        rmfilter_out = output

    matrix = distance_matrix(size)
    if method == "occurrence":
        matrix[matrix > 0] = 1
    elif method == "gravity":
        with np.errstate(divide="ignore"):
            denom = np.power(matrix, gamma)
            matrix = scale / denom
            matrix[denom == 0] = 0
    else:
        matrix_ = scale * np.exp(-2 * matrix / gamma)
        matrix = np.where(matrix > 0, matrix_, 0)

    path = gcore.tempfile()
    global TMPFILE
    TMPFILE = path

    with open(path, "w") as f:
        f.write(write_filter(matrix))
    gcore.message(_("Running development pressure filter..."))
    gcore.run_command("r.mfilter",
                      input=rmfilter_inp,
                      output=rmfilter_out,
                      filter=path)

    if flags["n"]:
        gcore.run_command(
            "g.region",
            n=region["n"],
            s=region["s"],
            e=region["e"],
            w=region["w"],
        )
        grast.mapcalc(
            exp="{out} = if(isnull({temp_null}), {rmfilter_out}, null())".
            format(temp_null=temp_map_nulls,
                   rmfilter_out=rmfilter_out,
                   out=output))
        gcore.del_temp_region()

    grast.raster_history(output)
def main():
    options, flags = gcore.parser()
    aspect = options['aspect']
    speed = options['speed']
    probability = options['probability']
    if options['particle_base']:
        particle_base = options['particle_base'] + '_'
    else:
        particle_base = None
    if options['particles']:
        particles = options['particles']
        min_size = float(options['min_size'])
        max_size = float(options['max_size'])
        comet_length = int(options['comet_length'])
    else:
        particles = min_size = max_size = comet_length = None
    try:
        total_time = int(options['total_time'])
        step = int(options['step'])
        age = int(options['age'])
        count = int(options['count'])
    except ValueError:
        gcore.fatal(_("Parameter should be integer"))

    gcore.use_temp_region()

    # create aspect in x and y direction
    aspect_x = 'aspect_x_' + str(os.getpid())
    aspect_y = 'aspect_y_' + str(os.getpid())
    xshift_tmp = 'xshift_tmp_' + str(os.getpid())
    yshift_tmp = 'yshift_tmp_' + str(os.getpid())
    TMP_RAST.append(aspect_x)
    TMP_RAST.append(aspect_y)
    grast.mapcalc(exp="{aspect_x} = cos({aspect})".format(aspect_x=aspect_x, aspect=aspect))
    grast.mapcalc(exp="{aspect_y} = sin({aspect})".format(aspect_y=aspect_y, aspect=aspect))
    grast.mapcalc(exp="{xshift} = {aspect_x}*{speed}*{t}".format(xshift=xshift_tmp, t=step, speed=speed,
                                                                 aspect_x=aspect_x), overwrite=True)
    grast.mapcalc(exp="{yshift} = {aspect_y}*{speed}*{t}".format(yshift=yshift_tmp, t=step, speed=speed,
                                                                 aspect_y=aspect_y), overwrite=True)

    # initialize
    vector_tmp1 = 'vector_tmp1_' + str(os.getpid())
    vector_tmp2 = 'vector_tmp2_' + str(os.getpid())
    vector_tmp3 = 'vector_tmp3_' + str(os.getpid())
    vector_region = 'vector_region_' + str(os.getpid())
    TMP_VECT.extend([vector_tmp1, vector_tmp2, vector_tmp3, vector_region])
    random_tmp = 'random_tmp_' + str(os.getpid())
    TMP_RAST.extend([xshift_tmp, yshift_tmp, random_tmp])
    gcore.run_command('v.in.region', output=vector_region, type='area')

    loop = 0
    vector_1 = particle_base + "{0:03d}".format(loop)
    generate_points(name=vector_1, probability_map=probability, count=count)

    grast.mapcalc(exp="{random} = int(rand(1, {maxt}))".format(random=random_tmp, maxt=age + 1))
    gcore.run_command('v.what.rast', map=vector_1, raster=random_tmp, column='t')
    write_vect_history('v.particles', options, flags, vector_1)
    vector_names = [vector_1, ]
    for time in range(0, total_time + step, step):
        vector_1 = particle_base + "{0:03d}".format(loop)
        vector_2 = particle_base + "{0:03d}".format(loop + 1)
        vector_names.append(vector_2)

        gcore.run_command('v.what.rast', map=vector_1, raster=xshift_tmp, column='xshift')
        gcore.run_command('v.what.rast', map=vector_1, raster=yshift_tmp, column='yshift')
        gcore.run_command('v.transform', layer=1, input=vector_1, output=vector_2,
                          columns='xshift:xshift,yshift:yshift', quiet=True)
        # increase age
        gcore.info("Increasing age...")
        sql = 'UPDATE {table} SET t=t+1;'.format(table=vector_2)
        gcore.run_command('db.execute', sql=sql)

        # remove old points
        gcore.info("Removing old points...")
        gcore.run_command('v.select', overwrite=True, ainput=vector_2, atype='point',
                          binput=vector_region, btype='area', operator='within', output=vector_tmp1)
        gcore.run_command('v.extract', input=vector_tmp1, layer=1, type='point',
                          where="t <= " + str(age) + " AND xshift IS NOT NULL", output=vector_tmp2, overwrite=True)

        # generate new points
        gcore.info("Generating new points...")
        count_to_generate = count - gvect.vector_info(vector_tmp2)['points']
        if count_to_generate > 0:
            generate_points(name=vector_tmp3, probability_map=probability,
                            count=count_to_generate, overwrite=True)

            gcore.info("Patchig new and old points...")
            gcore.run_command('v.patch', flags='e', input=[vector_tmp2, vector_tmp3],
                              output=vector_2, overwrite=True)
            sql = 'UPDATE {table} SET t={t} WHERE t IS NULL;'.format(table=vector_2, t=0)
            gcore.run_command('db.execute', sql=sql)
            
        write_vect_history('v.particles', options, flags, vector_2)

        loop += 1
    # Make sure the temporal database exists
    tgis.init()

    tgis.open_new_space_time_dataset(particle_base[:-1], type='stvds',
                                     temporaltype='relative',
                                     title="title", descr='desc',
                                     semantic='mean', dbif=None,
                                     overwrite=gcore.overwrite())
    # TODO: we must start from 1 because there is a bug in register_maps_in_space_time_dataset
    tgis.register_maps_in_space_time_dataset(
        type='vect', name=particle_base[:-1], maps=','.join(vector_names),
        start=str(1), end=None, unit='seconds', increment=step,
        interval=False, dbif=None)
        
    # create one vector map with multiple layers
    fd, path = tempfile.mkstemp(text=True)
    tmpfile = open(path, 'w')
    k = 0
    for vector in vector_names:
        k += 1
        layers = [x for x in range(k - comet_length + 1, k + 1) if x > 0]
        categories = list(range(len(layers), 0, -1))
        text = ''
        for layer, cat in zip(layers, categories):
            text += '{l} {c}\n'.format(l=layer, c=cat)
        coords = gcore.read_command('v.to.db', flags='p', quiet=True, map=vector,
                                    type='point', option='coor', separator=" ").strip()
        for coord in coords.split('\n'):
            coord = coord.split()
            tmpfile.write('P 1 {n_cat}\n{x} {y}\n'.format(n_cat=len(categories), x=coord[1], y=coord[2]))
            tmpfile.write(text)
    tmpfile.close()

    gcore.run_command('v.in.ascii', flags='n', overwrite=True, input=path, output=particles,
                      format='standard', separator=" ")
    os.close(fd)
    os.remove(path)
    k = 0
    sql = []
    sizes = get_sizes(max_size, min_size, comet_length)
    temporal_maps = []
    for vector in vector_names:
        k += 1
        table = 't' + str(k)
        gcore.run_command('v.db.addtable', map=particles, table=table, layer=k,
                          column="width double precision")
        temporal_maps.append(particles + ':' + str(k))
        for i in range(comet_length):
            sql.append("UPDATE {table} SET width={w:.1f} WHERE cat={c}".format(table=table,
                                                                               w=sizes[i][1], c=sizes[i][0]))
    gcore.write_command('db.execute', input='-', stdin=';\n'.join(sql))

    tgis.open_new_space_time_dataset(particles, type='stvds',
                                     temporaltype='relative',
                                     title="title", descr='desc',
                                     semantic='mean', dbif=None,
                                     overwrite=True)
    # TODO: we must start from 1 because there is a bug in register_maps_in_space_time_dataset
    tgis.register_maps_in_space_time_dataset(
        type='vect', name=particles, maps=','.join(temporal_maps),
        start=str(1), end=None, unit='seconds', increment=step,
        interval=False, dbif=None)

    write_vect_history('v.particles', options, flags, particles)
Ejemplo n.º 15
0
 def setUpClass(cls):
     gcore.use_temp_region()
     gcore.run_command("g.region", raster="elevation")
Ejemplo n.º 16
0
def main():
    options, flags = gcore.parser()

    location = options["location"]
    mapset = options["mapset"]
    dbase = options["dbase"]

    resolution = options["resolution"]
    if resolution:
        resolution = float(resolution)
    method = options["method"]
    curr_region = flags["r"]

    transform_z = flags["z"]
    overwrite = flags["o"]

    if not curr_region:
        gcore.use_temp_region()
        atexit.register(gcore.del_temp_region)
    if overwrite or gcore.overwrite():
        overwrite = True
    else:
        overwrite = False
    #
    # r.proj
    #
    parameters = dict(location=location,
                      mapset=mapset,
                      flags="l",
                      overwrite=overwrite)
    if dbase:
        parameters.update(dict(dbase=dbase))
    # first run r.proj to see if it works
    try:
        gcore.run_command("r.proj", quiet=True, **parameters)
    except CalledModuleError:
        gcore.fatal(
            _("Module r.proj failed. Please check the error messages above."))
    # run again to get the raster maps
    rasters = gcore.read_command("r.proj", **parameters)
    rasters = rasters.strip().split()
    gcore.info(
        _("{num} raster maps will be reprojected from mapset <{mapsetS}> "
          "to mapset <{mapsetT}>.").format(num=len(rasters),
                                           mapsetS=mapset,
                                           mapsetT=gcore.gisenv()["MAPSET"]))

    parameters = dict(location=location,
                      mapset=mapset,
                      method=method,
                      overwrite=overwrite)
    if resolution:
        parameters.update(dict(resolution=resolution))
    if dbase:
        parameters.update(dict(dbase=dbase))
    for raster in rasters:
        if not curr_region:
            bounds = gcore.read_command("r.proj",
                                        input=raster,
                                        flags="g",
                                        **parameters)
            bounds = parse_key_val(bounds, vsep=" ")
            gcore.run_command("g.region", **bounds)

        gcore.run_command("r.proj", input=raster, **parameters)

    #
    # v.proj
    #
    parameters = dict(location=location,
                      mapset=mapset,
                      flags="l",
                      overwrite=overwrite)
    if dbase:
        parameters.update(dict(dbase=dbase))
    # first run v.proj to see if it works
    try:
        gcore.run_command("v.proj", quiet=True, **parameters)
    except CalledModuleError:
        gcore.fatal(
            _("Module v.proj failed. Please check the error messages above."))
    # run again to get the vector maps
    vectors = gcore.read_command("v.proj", **parameters)
    vectors = vectors.strip().split()
    gcore.info(
        _("{num} vectors maps will be reprojected from mapset <{mapsetS}> "
          "to mapset <{mapsetT}>.").format(num=len(vectors),
                                           mapsetS=mapset,
                                           mapsetT=gcore.gisenv()["MAPSET"]))

    parameters = dict(location=location, mapset=mapset, overwrite=overwrite)
    if transform_z:
        parameters.update(dict(flags="z"))
    for vector in vectors:
        gcore.run_command("v.proj", input=vector, **parameters)
Ejemplo n.º 17
0
def main():
    options, flags = gcore.parser()

    # it does not check if pngs and other files exists,
    # maybe it could check the any/all file(s) dir

    if options['raster'] and options['strds']:
        gcore.fatal(_("Options raster and strds cannot be specified together."
                      " Please decide for one of them."))
    if options['raster'] and options['where']:
        gcore.fatal(_("Option where cannot be combined with the option raster."
                      " Please don't set where option or use strds option"
                      " instead of raster option."))
    if options['raster']:
        if ',' in options['raster']:
            maps = options['raster'].split(',')  # TODO: skip empty parts
        else:
            maps = [options['raster']]
    elif options['strds']:
        # import and init only when needed
        # init is called anyway when the generated form is used
        import grass.temporal as tgis

        strds = options['strds']
        where = options['where']

        # make sure the temporal database exists
        tgis.init()

        # create the space time raster object
        ds = tgis.open_old_space_time_dataset(strds, 'strds')
        # check if the dataset is in the temporal database
        if not ds.is_in_db():
            gcore.fatal(_("Space time dataset <%s> not found") % strds)

        # we need a database interface
        dbiface = tgis.SQLDatabaseInterfaceConnection()
        dbiface.connect()

        # the query
        rows = ds.get_registered_maps(columns='id', where=where, order='start_time')
        if not rows:
            gcore.fatal(_("Cannot get any maps for spatio-temporal raster"
                          " dataset <%s>."
                          " Dataset is empty or you temporal WHERE"
                          " condition filtered all maps out."
                          " Please, specify another dataset,"
                          " put maps into this dataset"
                          " or correct your WHERE condition.") % strds)
        maps = [row['id'] for row in rows]
    else:
        gcore.fatal(_("Either raster or strds option must be specified."
                      " Please specify one of them."))
    # get the number of maps for later use
    num_maps = len(maps)

    out_dir = options['output']
    if not os.path.exists(out_dir):
        # TODO: maybe we could create the last dir on specified path?
        gcore.fatal(_("Output path <%s> does not exists."
                      " You need to create the (empty) output directory"
                      " yourself before running this module.") % out_dir)
    epsg = int(options['epsg'])

    if ',' in options['opacity']:
        opacities = [float(opacity)
                     for opacity in options['opacity'].split(',')]
        if len(opacities) != num_maps:
            gcore.fatal(_("Number of opacities <{no}> does not match number"
                          " of maps <{nm}>.").format(no=len(opacities),
                                                     nm=num_maps))
    else:
        opacities = [float(options['opacity'])] * num_maps

    if ',' in options['info']:
        infos = options['info'].split(',')
    else:
        infos = [options['info']]

    # r.out.png options
    compression = int(options['compression'])
    # flag w is passed to r.out.png.proj
    # our flag n is inversion of r.out.png.proj's t flag
    # (transparent NULLs are better for overlay)
    # we always need the l flag (ll .wgs84 file)
    routpng_flags = ''
    if not flags['n']:
        routpng_flags += 't'
    if flags['w']:
        routpng_flags += 'w'
    # r.out.png.proj l flag for LL .wgs84 file is now function parameter
    # and is specified bellow

    if flags['m']:
        use_region = False
        # we will use map extent
        gcore.use_temp_region()
    else:
        use_region = True

    # hard coded file names
    data_file_name = 'data_file.csv'
    js_data_file_name = 'data_file.js'

    data_file = open(os.path.join(out_dir, data_file_name), 'w')
    js_data_file = open(os.path.join(out_dir, js_data_file_name), 'w')
    js_data_file.write('/* This file was generated by r.out.leaflet GRASS GIS'
                       ' module. */\n\n')
    js_data_file.write('var layerInfos = [\n')

    for i, map_name in enumerate(maps):
        if not use_region:
            if gcore.run_command('g.region', rast=map_name):
                raise RuntimeError("Cannot set region from map <%s>."
                                   % map_name)
        if '@' in map_name:
            pure_map_name = map_name.split('@')[0]
        else:
            pure_map_name = map_name
        # TODO: mixing current and map's mapset at this point
        if '@' in map_name:
            map_name, src_mapset_name = map_name.split('@')
        else:
            # TODO: maybe mapset is mandatory for those out of current mapset?
            src_mapset_name = gcore.gisenv()['MAPSET']
        image_file_name = pure_map_name + '.png'
        image_file_path = os.path.join(out_dir, image_file_name)
        # TODO: skip writing to file and extract the information from
        # function, or use object if function is so large
        wgs84_file = image_file_path + '.wgs84'
        export_png_in_projection(map_name=map_name,
                                 src_mapset_name=src_mapset_name,
                                 output_file=image_file_path,
                                 epsg_code=epsg,
                                 compression=compression,
                                 routpng_flags=routpng_flags,
                                 wgs84_file=wgs84_file,
                                 use_region=True)

        data_file.write(pure_map_name + ',' + image_file_name + '\n')

        # it doesn't matter in which location we are, it just uses the current
        # location, not tested for LL loc, assuming that to be nop.
        map_extent = get_map_extent_for_file(wgs84_file)
        bounds = map_extent_to_js_leaflet_list(map_extent)

        extra_attributes = []

        generate_infos(map_name=map_name,
                       projected_png_file=image_file_path,
                       required_infos=infos,
                       output_directory=out_dir,
                       attributes=extra_attributes)
        # http://www.w3schools.com/js/js_objects.asp
        js_data_file.write("""   {{title: "{title}", file: "{file_}","""
                           """ bounds: {bounds}, opacity: {opacity}"""
                           .format(title=pure_map_name,
                                   file_=image_file_name,
                                   bounds=bounds,
                                   opacity=opacities[i]))
        if extra_attributes:
            extra_js_attributes = [pair[0] + ': "' +
                                   escape_quotes(
                                       escape_endlines(
                                           escape_backslashes(
                                               pair[1]
                                           )))
                                   + '"'
                                   for pair in extra_attributes]
            js_data_file.write(', ' + ', '.join(extra_js_attributes))
        js_data_file.write("""}\n""")
        # do not write after the last item
        if i < num_maps - 1:
            js_data_file.write(',')
    js_data_file.write('];\n')
    data_file.close()
Ejemplo n.º 18
0
 def setUpClass(cls):
     gcore.use_temp_region()
     gcore.run_command('g.region', rast='elevation')
Ejemplo n.º 19
0
def main():
    size = int(options['size'])
    gamma = scale = None
    if options['gamma']:
        gamma = float(options['gamma'])
    if options['scaling_factor']:
        scale = float(options['scaling_factor'])
    input_dev = options['input']
    output = options['output']
    method = options['method']

    if method in ('gravity', 'kernel') and (gamma is None or scale is None):
        gcore.fatal(
            _("Methods gravity and kernel require options scaling_factor and gamma"
              ))

    temp_map = 'tmp_futures_devPressure_' + str(os.getpid()) + '_copy'
    temp_map_out = 'tmp_futures_devPressure_' + str(os.getpid()) + '_out'
    temp_map_nulls = 'tmp_futures_devPressure_' + str(os.getpid()) + '_nulls'
    global TMP, TMPFILE
    if flags['n']:
        gcore.message(_("Preparing data..."))
        region = gcore.region()
        gcore.use_temp_region()
        gcore.run_command('g.region',
                          n=region['n'] + size * region['nsres'],
                          s=region['s'] - size * region['nsres'],
                          e=region['e'] + size * region['ewres'],
                          w=region['w'] - size * region['ewres'])
        TMP.append(temp_map)
        TMP.append(temp_map_nulls)
        TMP.append(temp_map_out)
        exp = "{temp_map_nulls} = if(isnull({inp}), 1, null())".format(
            temp_map_nulls=temp_map_nulls, inp=input_dev)
        grast.mapcalc(exp=exp)
        grast.mapcalc(exp="{temp} = if(isnull({inp}), 0, {inp})".format(
            temp=temp_map, inp=input_dev))
        rmfilter_inp = temp_map
        rmfilter_out = temp_map_out
    else:
        rmfilter_inp = input_dev
        rmfilter_out = output

    matrix = distance_matrix(size)
    if method == 'occurrence':
        matrix[matrix > 0] = 1
    elif method == 'gravity':
        with np.errstate(divide='ignore'):
            denom = np.power(matrix, gamma)
            matrix = scale / denom
            matrix[denom == 0] = 0
    else:
        matrix_ = scale * np.exp(-2 * matrix / gamma)
        matrix = np.where(matrix > 0, matrix_, 0)

    path = gcore.tempfile()
    global TMPFILE
    TMPFILE = path

    with open(path, 'w') as f:
        f.write(write_filter(matrix))
    gcore.message(_("Running development pressure filter..."))
    gcore.run_command('r.mfilter',
                      input=rmfilter_inp,
                      output=rmfilter_out,
                      filter=path)

    if flags['n']:
        gcore.run_command(
            'g.region',
            n=region['n'],
            s=region['s'],
            e=region['e'],
            w=region['w'],
        )
        grast.mapcalc(
            exp="{out} = if(isnull({temp_null}), {rmfilter_out}, null())".
            format(temp_null=temp_map_nulls,
                   rmfilter_out=rmfilter_out,
                   out=output))
        gcore.del_temp_region()

    grast.raster_history(output)