def cleanup():
    if RREMOVE or VREMOVE:
        gcore.info(_("Cleaning temporary maps..."))
    for rast in RREMOVE:
        gscript.run_command('g.remove', flags='f', type='raster', name=rast, quiet=True)
    for vect in VREMOVE:
        gscript.run_command('g.remove', flags='f', type='vector', name=vect, quiet=True)
示例#2
0
def parseModules():
    """Parse modules' interface"""
    modules = dict()

    # list of modules to be ignored
    ignore = [
        "g.mapsets_picker.py", "v.type_wrapper.py", "g.parser", "vcolors"
    ]

    count = len(grassCmd)
    i = 0
    for module in grassCmd:
        i += 1
        if i % 10 == 0:
            grass.info("* %d/%d" % (i, count))
        if module in ignore:
            continue
        try:
            interface = gtask.parse_interface(module)
        except Exception as e:
            grass.error(module + ": " + str(e))
            continue
        modules[interface.name] = {
            "label": interface.label,
            "desc": interface.description,
            "keywords": interface.keywords,
        }

    return modules
示例#3
0
def parseModules():
    """Parse modules' interface"""
    modules = dict()

    # list of modules to be ignored
    ignore = ['g.mapsets_picker.py',
              'v.type_wrapper.py',
              'g.parser',
              'vcolors']

    count = len(grassCmd)
    i = 0
    for module in grassCmd:
        i += 1
        if i % 10 == 0:
            grass.info('* %d/%d' % (i, count))
        if module in ignore:
            continue
        try:
            interface = gtask.parse_interface(module)
        except Exception as e:
            grass.error(module + ': ' + str(e))
            continue
        modules[interface.name] = {'label': interface.label,
                                   'desc': interface.description,
                                   'keywords': interface.keywords}

    return modules
def cleanup():
    if len(TMP_RAST + TMP_VECT):
        gcore.info(_("Cleaning %d temporary maps...") % len(TMP_RAST + TMP_VECT))

    gcore.run_command('g.remove', rast=','.join(TMP_RAST), quiet=True)
    gcore.run_command('g.remove', vect=','.join(TMP_VECT), quiet=True)
    gcore.del_temp_region()
示例#5
0
def parseModules():
    """Parse modules' interface"""
    modules = dict()

    # list of modules to be ignored
    ignore = ['g.mapsets_picker.py',
              'v.type_wrapper.py',
              'g.parser',
              'vcolors']

    count = len(grassCmd)
    i = 0
    for module in grassCmd:
        i += 1
        if i % 10 == 0:
            grass.info('* %d/%d' % (i, count))
        if module in ignore:
            continue
        try:
            interface = gtask.parse_interface(module)
        except Exception as e:
            grass.error(module + ': ' + str(e))
            continue
        modules[interface.name] = {'label': interface.label,
                                   'desc': interface.description,
                                   'keywords': interface.keywords}

    return modules
示例#6
0
def cleanup():
    if len(TMP):
        core.info(_("Cleaning %d temporary maps...") % len(TMP))
    for rast in TMP:
        grass.run_command('g.remove',
                          type='raster',
                          name=rast,
                          flags='f',
                          quiet=True)
示例#7
0
def main():
    # check dependecies
    if sys.platform != "win32":
        check_progs()
    
    # define path
    if flags['s']:
        options['prefix'] = os.environ['GISBASE']
    if options['prefix'] == '$GRASS_ADDON_PATH':
        if not os.environ.has_key('GRASS_ADDON_PATH') or \
                not os.environ['GRASS_ADDON_PATH']:
            major_version = int(grass.version()['version'].split('.', 1)[0])
            grass.warning(_("GRASS_ADDON_PATH is not defined, "
                            "installing to ~/.grass%d/addons/") % major_version)
            options['prefix'] = os.path.join(os.environ['HOME'], '.grass%d' % major_version, 'addons')
        else:
            path_list = os.environ['GRASS_ADDON_PATH'].split(os.pathsep)
            if len(path_list) < 1:
                grass.fatal(_("Invalid GRASS_ADDON_PATH value - '%s'") % os.environ['GRASS_ADDON_PATH'])
            if len(path_list) > 1:
                grass.warning(_("GRASS_ADDON_PATH has more items, using first defined - '%s'") % path_list[0])
            options['prefix'] = path_list[0]
    
    # list available modules
    if flags['l'] or flags['c'] or flags['g']:
        list_available_extensions()
        return 0
    elif flags['a']:
        elist = get_installed_extensions()
        if elist:
            grass.message(_("List of installed extensions:"))
            sys.stdout.write('\n'.join(elist))
            sys.stdout.write('\n')
        else:
            grass.info(_("No extension installed"))
        return 0
    else:
        if not options['extension']:
            grass.fatal(_('You need to define an extension name or use -l'))

    if flags['d']:
        if options['operation'] != 'add':
            grass.warning(_("Flag 'd' is relevant only to 'operation=add'. Ignoring this flag."))
        else:
            global remove_tmpdir
            remove_tmpdir = False
    
    if options['operation'] == 'add':
        check_dirs()
        install_extension()
    else: # remove
        remove_extension(flags['f'])
    
    return 0
示例#8
0
def main():
    # check dependecies
    if sys.platform != "win32":
        check_progs()
    
    # define path
    if flags['s']:
        options['prefix'] = os.environ['GISBASE']
    if options['prefix'] == '$GRASS_ADDON_PATH':
        if not os.environ.has_key('GRASS_ADDON_PATH') or \
                not os.environ['GRASS_ADDON_PATH']:
            major_version = int(grass.version()['version'].split('.', 1)[0])
            grass.warning(_("GRASS_ADDON_PATH is not defined, "
                            "installing to ~/.grass%d/addons/") % major_version)
            options['prefix'] = os.path.join(os.environ['HOME'], '.grass%d' % major_version, 'addons')
        else:
            path_list = os.environ['GRASS_ADDON_PATH'].split(os.pathsep)
            if len(path_list) < 1:
                grass.fatal(_("Invalid GRASS_ADDON_PATH value - '%s'") % os.environ['GRASS_ADDON_PATH'])
            if len(path_list) > 1:
                grass.warning(_("GRASS_ADDON_PATH has more items, using first defined - '%s'") % path_list[0])
            options['prefix'] = path_list[0]
    
    # list available modules
    if flags['l'] or flags['c'] or flags['g']:
        list_available_extensions()
        return 0
    elif flags['a']:
        elist = get_installed_extensions()
        if elist:
            grass.message(_("List of installed extensions:"))
            sys.stdout.write('\n'.join(elist))
            sys.stdout.write('\n')
        else:
            grass.info(_("No extension installed"))
        return 0
    else:
        if not options['extension']:
            grass.fatal(_('You need to define an extension name or use -l'))

    if flags['d']:
        if options['operation'] != 'add':
            grass.warning(_("Flag 'd' is relevant only to 'operation=add'. Ignoring this flag."))
        else:
            global remove_tmpdir
            remove_tmpdir = False
    
    if options['operation'] == 'add':
        check_dirs()
        install_extension()
    else: # remove
        remove_extension(flags['f'])
    
    return 0
示例#9
0
def remove_extension(force = False):
    # try to read XML metadata file first
    fXML = os.path.join(options['prefix'], 'modules.xml')
    name = options['extension']
    if name not in get_installed_extensions():
        grass.warning(_("Extension <%s> not found") % name)
    
    if force:
        grass.verbose(_("List of removed files:"))
    else:
        grass.info(_("Files to be removed (use flag 'f' to force removal):"))
    
    if os.path.exists(fXML):
        f = open(fXML, 'r')
        tree = etree.fromstring(f.read())
        flist = []
        for task in tree.findall('task'):
            if name == task.get('name', default = '') and \
                    task.find('binary') is not None:
                for f in task.find('binary').findall('file'):
                    flist.append(f.text)
        
        if flist:
            removed = False
            err = list()
            for fpath in flist:
                try:
                    if force:
                        grass.verbose(fpath)
                        os.remove(fpath)
                        removed = True
                    else:
                        print fpath
                except OSError:
                    err.append((_("Unable to remove file '%s'") % fpath))
            if force and not removed:
                grass.fatal(_("Extension <%s> not found") % options['extension'])
            
            if err:
                for e in err:
                    grass.error(e)
        else:
            remove_extension_std(force)
    else:
        remove_extension_std(force)

    if force:
        grass.message(_("Updating metadata file..."))
        remove_extension_xml()
        grass.message(_("Extension <%s> successfully uninstalled.") % options['extension'])
    else:
        grass.warning(_("Extension <%s> not removed.\n"
                        "Re-run '%s' with 'f' flag to force removal") % (options['extension'], 'g.extension'))
示例#10
0
def remove_extension(force = False):
    # try to read XML metadata file first
    fXML = os.path.join(options['prefix'], 'modules.xml')
    name = options['extension']
    if name not in get_installed_extensions():
        grass.warning(_("Extension <%s> not found") % name)
    
    if force:
        grass.verbose(_("List of removed files:"))
    else:
        grass.info(_("Files to be removed (use flag 'f' to force removal):"))
    
    if os.path.exists(fXML):
        f = open(fXML, 'r')
        tree = etree.fromstring(f.read())
        flist = []
        for task in tree.findall('task'):
            if name == task.get('name', default = '') and \
                    task.find('binary') is not None:
                for f in task.find('binary').findall('file'):
                    flist.append(f.text)
        
        if flist:
            removed = False
            err = list()
            for fpath in flist:
                try:
                    if force:
                        grass.verbose(fpath)
                        os.remove(fpath)
                        removed = True
                    else:
                        print fpath
                except OSError:
                    err.append((_("Unable to remove file '%s'") % fpath))
            if force and not removed:
                grass.fatal(_("Extension <%s> not found") % options['extension'])
            
            if err:
                for e in err:
                    grass.error(e)
        else:
            remove_extension_std(force)
    else:
        remove_extension_std(force)

    if force:
        grass.message(_("Updating metadata file..."))
        remove_extension_xml()
        grass.message(_("Extension <%s> successfully uninstalled.") % options['extension'])
    else:
        grass.warning(_("Extension <%s> not removed.\n"
                        "Re-run '%s' with 'f' flag to force removal") % (options['extension'], 'g.extension'))
示例#11
0
    def emit(self, record):
        """ Write the log message.

        :param record: record to emit
        """
        if record.levelno >= logging.ERROR:
            fatal(record.msg)
        elif record.levelno >= logging.WARNING:
            warning(record.msg)
        elif record.levelno >= logging.INFO:
            info(record.msg)
        elif record.levelno >= logging.DEBUG:
            debug(record.msg)
示例#12
0
def cleanup():
    if REMOVE or MREMOVE:
        core.info(_("Cleaning temporary maps..."))
    for rast in REMOVE:
        grass.run_command("g.remove", type="raster", name=rast, flags="f", quiet=True)
    for pattern in MREMOVE:
        grass.run_command(
            "g.remove",
            type="raster",
            pattern="{pattern}*".format(pattern=pattern),
            flags="f",
            quiet=True,
        )
示例#13
0
def cleanup():
    if RREMOVE or VREMOVE:
        gcore.info(_("Cleaning temporary maps..."))
    for rast in RREMOVE:
        gscript.run_command("g.remove",
                            flags="f",
                            type="raster",
                            name=rast,
                            quiet=True)
    for vect in VREMOVE:
        gscript.run_command("g.remove",
                            flags="f",
                            type="vector",
                            name=vect,
                            quiet=True)
示例#14
0
def cleanup():
    if REMOVE or MREMOVE:
        core.info(_("Cleaning temporary maps..."))
    for rast in REMOVE:
        grass.run_command('g.remove',
                          type='raster',
                          name=rast,
                          flags='f',
                          quiet=True)
    for pattern in MREMOVE:
        grass.run_command('g.remove',
                          type='raster',
                          pattern='{pattern}*'.format(pattern=pattern),
                          flags='f',
                          quiet=True)
示例#15
0
def remove_extension(force = False):
    if flags['t']:
        mlist = get_toolbox_modules(options['extension'])
    else:
        mlist = [options['extension']]

    if force:
        grass.verbose(_("List of removed files:"))
    else:
        grass.info(_("Files to be removed (use flag 'f' to force removal):"))

    remove_modules(mlist, force)

    if force:
        grass.message(_("Updating metadata file..."))
        remove_extension_xml(mlist)
        grass.message(_("Extension <%s> successfully uninstalled.") % options['extension'])
    else:
        grass.warning(_("Extension <%s> not removed.\n"
                        "Re-run '%s' with 'f' flag to force removal") % (options['extension'], 'g.extension'))
示例#16
0
def letantsdance(rounds, outrounds):
    """
    Organize the agents and the pheromone on the playground.
    """
    if world.addsequencenumber:
        outputmapbasename = \
            world.playground.grassmapnames[anthill.Anthill.RESULT].split("@")
    else:
        outputmapbasename = False
        outputmapname = False
    if 0 < outrounds < rounds:
        # calculate when to write output
        mainloops = rounds / outrounds
        nextwrite = outrounds
    else:
        # produce output only at the end
        mainloops = 1
        nextwrite = rounds
    run = 0
    while run < mainloops:
        if outputmapbasename:
            outputmapname = outputmapbasename[0] + str(run) + "@" + \
                            outputmapbasename[1]
        # loop and write out the contents at the end
        world.letantsdance(nextwrite)
        # Print the number of found paths
        grass.info("Number of found paths: " + str(world.numberofpaths))
        # export the value maps
        #TODO hopefully not really needed - workaround for broken(?) garray
        for i in range(len(world.playground.layers[anthill.Anthill.RESULT])):
            for j in range(
                    len(world.playground.layers[anthill.Anthill.RESULT][0])):
                world.playground.layers["copy"][i][j] = \
                        world.playground.layers[anthill.Anthill.RESULT][i][j]
        world.playground.writelayer("copy", outputmapname,
                                    world.overwritepheormone)
        #TODO world.playground.writelayer(anthill.Anthill.RESULT, False,
        #TODO                                    world.overwritepheormone)
        #        print "nrofpaths:", world.nrop
        # count down outer
        run += 1
示例#17
0
def main():
    if has_mask and has_mask3d:
        grass.info(_("[Raster and Volume MASKs present]"))
    elif has_mask:
        grass.info(_("[Raster MASK present]"))
    elif has_mask3d:
        grass.info(_("[Volume MASK present]"))

    return 0
示例#18
0
def main():
    options, flags = grass.parser()

    elevation_input = options['elevation']
    aspect_input = options['aspect']
    slope_input = options['slope']
    linke = options['linke']
    linke_value = options['linke_value']
    albedo = options['albedo']
    albedo_value = options['albedo_value']

    beam_rad_basename = options['beam_rad_basename']
    diff_rad_basename = options['diff_rad_basename']
    refl_rad_basename = options['refl_rad_basename']
    glob_rad_basename = options['glob_rad_basename']
    incidout_basename = options['incidout_basename']

    if not any([beam_rad_basename, diff_rad_basename,
                refl_rad_basename, glob_rad_basename,
                incidout_basename]):
        grass.fatal(_("No output specified."))

    start_time = float(options['start_time'])
    end_time = float(options['end_time'])
    time_step = float(options['time_step'])
    nprocs = int(options['nprocs'])
    day = int(options['day'])
    temporal = flags['t']
    binary = flags['b']
    binaryTmpName = 'binary'
    year = int(options['year'])

    if not is_grass_7() and temporal:
        grass.warning(_("Flag t has effect only in GRASS 7"))

    # check: start < end
    if start_time > end_time:
        grass.fatal(_("Start time is after end time."))
    if time_step >= end_time - start_time:
        grass.fatal(_("Time step is too big."))

    # here we check all the days
    if not grass.overwrite():
        check_time_map_names(beam_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)
        check_time_map_names(diff_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)
        check_time_map_names(refl_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)
        check_time_map_names(glob_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)

    # check for slope/aspect
    if not aspect_input or not slope_input:
        params = {}
        if not aspect_input:
            aspect_input = create_tmp_map_name('aspect')
            params.update({'aspect': aspect_input})
            TMP.append(aspect_input)
        if not slope_input:
            slope_input = create_tmp_map_name('slope')
            params.update({'slope': slope_input})
            TMP.append(slope_input)

        grass.info(_("Running r.slope.aspect..."))
        grass.run_command('r.slope.aspect', elevation=elevation_input,
                          quiet=True, **params)

    grass.info(_("Running r.sun in a loop..."))
    count = 0
    # Parallel processing
    proc_list = []
    proc_count = 0
    suffixes = []
    suffixes_all = []
    times = list(frange(start_time, end_time, time_step))
    num_times = len(times)
    core.percent(0, num_times, 1)
    for time in times:
        count += 1
        core.percent(count, num_times, 10)

        suffix = '_' + format_time(time)
        proc_list.append(Process(target=run_r_sun,
                                 args=(elevation_input, aspect_input,
                                       slope_input, day, time,
                                       linke, linke_value,
                                       albedo, albedo_value,
                                       beam_rad_basename,
                                       diff_rad_basename,
                                       refl_rad_basename,
                                       glob_rad_basename,
                                       incidout_basename,
                                       suffix,
                                       binary, binaryTmpName)))

        proc_list[proc_count].start()
        proc_count += 1
        suffixes.append(suffix)
        suffixes_all.append(suffix)

        if proc_count == nprocs or proc_count == num_times or count == num_times:
            proc_count = 0
            exitcodes = 0
            for proc in proc_list:
                proc.join()
                exitcodes += proc.exitcode

            if exitcodes != 0:
                core.fatal(_("Error while r.sun computation"))

            # Empty process list
            proc_list = []
            suffixes = []
    # FIXME: how percent really works?
    # core.percent(1, 1, 1)

    # add timestamps either via temporal framework in 7 or r.timestamp in 6.x
    if is_grass_7() and temporal:
        core.info(_("Registering created maps into temporal dataset..."))
        import grass.temporal as tgis

        def registerToTemporal(basename, suffixes, mapset, start_time,
                               time_step, title, desc):
            maps = ','.join([basename + suf + '@' + mapset for suf in suffixes])
            tgis.open_new_stds(basename, type='strds',
                               temporaltype='absolute',
                               title=title, descr=desc,
                               semantic='mean', dbif=None,
                               overwrite=grass.overwrite())
            tgis.register_maps_in_space_time_dataset(
                type='raster', name=basename, maps=maps, start=start_time,
                end=None, increment=time_step, dbif=None, interval=False)
        # Make sure the temporal database exists
        tgis.init()

        mapset = grass.gisenv()['MAPSET']
        absolute_time = datetime.datetime(year, 1, 1) + \
                        datetime.timedelta(days=day - 1) + \
                        datetime.timedelta(hours=start_time)
        start = absolute_time.strftime("%Y-%m-%d %H:%M:%S")
        step = datetime.timedelta(hours=time_step)
        step = "%d seconds" % step.seconds

        if beam_rad_basename:
            registerToTemporal(beam_rad_basename, suffixes_all, mapset, start,
                               step, title="Beam irradiance",
                               desc="Output beam irradiance raster maps [Wh.m-2]")
        if diff_rad_basename:
            registerToTemporal(diff_rad_basename, suffixes_all, mapset, start,
                               step, title="Diffuse irradiance",
                               desc="Output diffuse irradiance raster maps [Wh.m-2]")
        if refl_rad_basename:
            registerToTemporal(refl_rad_basename, suffixes_all, mapset, start,
                               step, title="Reflected irradiance",
                               desc="Output reflected irradiance raster maps [Wh.m-2]")
        if glob_rad_basename:
            registerToTemporal(glob_rad_basename, suffixes_all, mapset, start,
                               step, title="Total irradiance",
                               desc="Output total irradiance raster maps [Wh.m-2]")
        if incidout_basename:
            registerToTemporal(incidout_basename, suffixes_all, mapset, start,
                               step, title="Incidence angle",
                               desc="Output incidence angle raster maps")

    else:
        absolute_time = datetime.datetime(year, 1, 1) + \
                        datetime.timedelta(days=day - 1)
        for i, time in enumerate(times):
            grass_time = format_grass_time(absolute_time + datetime.timedelta(hours=time))
            if beam_rad_basename:
                set_time_stamp(beam_rad_basename + suffixes_all[i],
                               time=grass_time)
            if diff_rad_basename:
                set_time_stamp(diff_rad_basename + suffixes_all[i],
                               time=grass_time)
            if refl_rad_basename:
                set_time_stamp(refl_rad_basename + suffixes_all[i],
                               time=grass_time)
            if glob_rad_basename:
                set_time_stamp(glob_rad_basename + suffixes_all[i],
                               time=grass_time)
            if incidout_basename:
                set_time_stamp(incidout_basename + suffixes_all[i],
                               time=grass_time)

    if beam_rad_basename:
        maps = [beam_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if diff_rad_basename:
        maps = [diff_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if refl_rad_basename:
        maps = [refl_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if glob_rad_basename:
        maps = [glob_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if incidout_basename:
        maps = [incidout_basename + suf for suf in suffixes_all]
        set_color_table(maps)
示例#19
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) > 1 and argv[1] == '-d':
        printDiff = True
    else:
        printDiff = False

    if len(argv) > 1 and argv[1] == '-h':
        print(sys.stderr, __doc__, file=sys.stderr)
        return 1

    nuldev = file(os.devnull, 'w+')
    grass.info("Step 1: running make...")
    grass.call(['make'], stderr=nuldev)
    grass.info("Step 2: parsing modules...")
    modules = dict()
    modules = parseModules()
    grass.info("Step 3: reading menu data...")
    data = LayerManagerMenuData()
    grass.info("Step 4: updating menu data...")
    updateData(data, modules)

    if printDiff:
        tempFile = tempfile.NamedTemporaryFile()
        grass.info("Step 5: diff menu data...")
        writeData(data, tempFile.name)

        grass.call(['diff', '-u',
                    os.path.join('xml', 'menudata.xml'),
                    tempFile.name], stderr=nuldev)
    else:
        grass.info("Step 5: writing menu data (menudata.xml)...")
        writeData(data)

    return 0
示例#20
0
    def warp_import(self, file, map):
        """Wrap raster file using gdalwarp and import wrapped file
        into GRASS"""
        warpfile = self.tmp + 'warped.geotiff'
        tmpmapname = map + '_tmp'

        t_srs = grass.read_command('g.proj',
                                   quiet = True,
                                   flags = 'jf').rstrip('\n')
        if not t_srs:
            grass.fatal(_('g.proj failed'))
        
        grass.debug("gdalwarp -s_srs '%s' -t_srs '%s' -r %s %s %s %s" % \
                        (self.options['srs'], t_srs,
                         self.options['method'], self.options['warpoptions'],
                         file, warpfile))
        grass.verbose("Warping input file '%s'..." % os.path.basename(file))
        if self.options['warpoptions']:
            ps = subprocess.Popen(['gdalwarp',
                                   '-s_srs', '%s' % self.options['srs'],
                                   '-t_srs', '%s' % t_srs,
                                   '-r', self.options['method'],
                                   self.options['warpoptions'],
                                   file, warpfile])
        else:
            ps = subprocess.Popen(['gdalwarp',
                                   '-s_srs', '%s' % self.options['srs'],
                                   '-t_srs', '%s' % t_srs,
                                   '-r', self.options['method'],
                                   file, warpfile])
            
        ps.wait()
        if ps.returncode != 0 or \
                not os.path.exists(warpfile):
            grass.fatal(_('gdalwarp failed'))
    
        # import it into a temporary map
        grass.info(_('Importing raster map...'))
        if grass.run_command('r.in.gdal',
                             quiet = True,
                             flags = self.gdal_flags,
                             input = warpfile,
                             output = tmpmapname) != 0:
            grass.fatal(_('r.in.gdal failed'))
        
        os.remove(warpfile)

        # get list of channels
        pattern = tmpmapname + '*'
        grass.debug('Pattern: %s' % pattern)
        mapset = grass.gisenv()['MAPSET']
        channel_list = grass.mlist_grouped(type = 'rast', pattern = pattern, mapset = mapset)[mapset]
        grass.debug('Channel list: %s' % ','.join(channel_list))
        
        if len(channel_list) < 2: # test for single band data
            self.channel_suffixes = []
        else:
            self.channel_suffixes = channel_list # ???
        
        grass.debug('Channel suffixes: %s' % ','.join(self.channel_suffixes))
        
        # add to the list of all suffixes
        self.suffixes = self.suffixes + self.channel_suffixes
        self.suffixes.sort()
        
        # get last suffix
        if len(self.channel_suffixes) > 0:
            last_suffix = self.channel_suffixes[-1]
        else:
            last_suffix = ''

        # find the alpha layer
        if self.flags['k']:
            alphalayer = tmpmapname + last_suffix
        else:
            alphalayer = tmpmapname + '.alpha'
        
        # test to see if the alpha map exists
        if not grass.find_file(element = 'cell', name = alphalayer)['name']:
            alphalayer = ''
        
        # calculate the new maps:
        for suffix in self.channel_suffixes:
            grass.debug("alpha=%s MAPsfx=%s%s tmpname=%s%s" % \
                            (alphalayer, map, suffix, tmpmapname, suffix))
            if alphalayer:
                # Use alpha channel for nulls: problem: I've seen a map
                # where alpha was 1-255; 1 being transparent. what to do?
                # (Geosci Australia Gold layer, format=tiff)
                if grass.run_command('r.mapcalc',
                                     quiet = True,
                                     expression = "%s%s = if(%s, %s%s, null())" % \
                                         (map, sfx, alphalayer, tmpmapname, sfx)) != 0:
                    grass.fatal(_('r.mapcalc failed'))
            else:
                if grass.run_command('g.copy',
                                     quiet = True,
                                     rast = "%s%s,%s%s" % \
                                         (tmpmapname, suffix, map, suffix)) != 0:
                    grass.fatal(_('g.copy failed'))
        
            # copy the color tables
            if grass.run_command('r.colors',
                                 quiet = True,
                                 map = map + suffix,
                                 rast = tmpmapname + suffix) != 0:
                grass.fatal(_('g.copy failed'))

            # make patch lists
            suffix = suffix.replace('.', '_')
            # this is a hack to make the patch lists empty:
            if self.tiler == 0:
                self.patches = []
            self.patches = self.patches.append(map + suffix)
    
        # if no suffix, processing is simple (e.g. elevation has only 1
        # band)
        if len(channel_list) < 2:
            # run r.mapcalc to crop to region
            if grass.run_command('r.mapcalc',
                                 quiet = True,
                                 expression = "%s = %s" % \
                                     (map, tmpmapname)) != 0:
                grass.fatal(_('r.mapcalc failed'))
            
            if grass.run_command('r.colors',
                                 quiet = True,
                                 map = map,
                                 rast = tmpmapname) != 0:
                grass.fatal(_('r.colors failed'))
    
        # remove the old channels
        if grass.run_command('g.remove',
                             quiet = True,
                             rast = ','.join(channel_list)) != 0:
            grass.fatal(_('g.remove failed'))
示例#21
0
    def run(self):
        # import tiles
        tiler = 0
        for input in self.options['input'].split(','):
            tmptilename = self.options['output'] + '_tile_' + str(tiler)
            if not os.path.exists(input):
                grass.warning(_("Missing input '%s'") % input)
                continue
            grass.info(_("Importing tile '%s'...") % os.path.basename(input))
            if self.flags['p']:
                self.nowarp_import(input, tmptilename)
            else:
                self.warp_import(input, tmptilename)
            
            self.maplist.append(tmptilename)
            tiler += 1
        
        if tiler < 1:
            grass.message(_("Nothing imported"))
            return 0
        
        # if there's more than one tile patch them together, otherwise
        # just rename that tile.
        if tiler == 1:
            if len(self.channel_suffixes) > 0:
                # multi-band
                for suffix in self.channel_suffixes:
                    # rename tile 0 to be the output
                    ffile = self.options['output'] + '_tile_0' + suffix
                    tfile = self.options['output'] + suffix
                    if grass.run_command('g.rename',
                                         quiet = True,
                                         rast = ffile + ',' + tfile) != 0:
                        grass.fatal(_('g.rename failed'))
            else: # single-band, single-tile
                ffile = self.options['output'] + '_tile_0' # + sfx ?
                tfile = self.options['output'] # + sfx ?
                if grass.run_command('g.rename',
                                     quiet = True,
                                     rast = ffile + ',' + tfile) != 0:
                    grass.fatal(_('g.rename failed'))
        else:
            # patch together each channel
            grass.debug('suffixes: %s' % ','.join(suffixes))
            if len(suffixes) > 0:
                # multi-band data
                for suffix in suffixes:
                    suffix = suffix.replace('.', '_')
                    # patch these together (using nulls only)
                    grass.message(_("Patching '%s' channel...") % suffix)
                    if grass.run_command('r.patch',
                                         quiet = True,
                                         input = patches, # ???
                                         output = self.options['output'] + suffix) != 0:
                        grass.fatal(_('r.patch failed'))
                        
                    # remove the temporary patches we made
                    if grass.run_command('g.remove',
                                         quiet = True,
                                         rast = patches) != 0:
                        grass.fatal(_('g.remove failed'))
            else:
                # single-band data
                grass.info(_("Patching tiles (this may take some time)..."))
                grass.debug("patch list = %s" % ','.join(maplist))

                # HACK: for 8bit PNG, GIF all the different tiles can have
                #   different color tables so patches output end up all freaky.
                #	r.mapcalc r#,g#,b# manual patching + r.composite?
                #	or d.out.file + r.in.png + r.region?
                # *** there is a GDAL utility to do this: gdal_merge.py
                #       http://www.gdal.org/gdal_merge.html
                for color in ('r', 'g', 'b'):
                    maplist_color = []
                    for map in maplist:
                        outmap = map + '_' + color
                        maplist_color.append(outmap)
                        if grass.run_command('r.mapcalc',
                                             quiet = True,
                                             expression = '%s = %s#%s' % (outmap, color, map)) != 0:
                            grass.fatal(_('r.mapcalc failed'))
                        if grass.run_command('r.colors',
                                             quiet = True,
                                             map = outmap,
                                             color = 'grey255') != 0:
                            grass.fatal(_('r.colors failed'))
                        if grass.run_command('r.null',
                                             quiet = True,
                                             map = outmap,
                                             setnull = 255) != 0:
                            grass.fatal(_('r.null failed'))
                
                        if grass.run_command('r.patch',
                                             input = ','.join(maplist_color),
                                             output = outmap + '_all') != 0:
                            grass.fatal(_('r.patch failed'))
                
                if grass.run_command('r.composite',
                                     quiet = True,
                                     red = map + '_r_all',
                                     green = map + '_g_all',
                                     blue = map + '_b_all',
                                     output = self.options['output']) != 0:
                    grass.fatal(_('r.composite failed'))

                if grass.run_command('g.mremove',
                                     quiet = True,
                                     flags = 'f',
                                     rast = map + '*') != 0:
                    grass.fatal(_('g.remove failed'))

        # there's already a no suffix, can't make colors
        # can only go up from here ;)
        colors = 0
        for suffix in self.suffixes:
            if suffix in ('.red', '.green', '.blue'):
                colors += 1
        
        # make a composite image if asked for and colors exist
        if colors == 3 and self.flags['c']:
            grass.message(_("Building color image <%s>...") % self.options['output'])
            if grass.run_command('r.composite',
                                 quiet = True,
                                 red = self.options['output'] + '.red',
                                 green = self.options['output'] + '.green',
                                 blue = self.options['output'] + '.blue',
                                 output = self.options['output']) != 0:
                grass.fatal(_('r.composite failed'))
        
        return 0
示例#22
0
def main():
    # check dependecies
    if sys.platform != "win32":
        check_progs()

    # manage proxies
    global PROXIES
    if options['proxy']:
        PROXIES = {}
        for ptype, purl in (p.split('=') for p in options['proxy'].split(',')):
            PROXIES[ptype] = purl

    # define path
    if flags['s']:
        options['prefix'] = os.environ['GISBASE']
    if options['prefix'] == '$GRASS_ADDON_BASE':
        if not os.getenv('GRASS_ADDON_BASE'):
            grass.warning(_("GRASS_ADDON_BASE is not defined, "
                            "installing to ~/.grass%s/addons") % version[0])
            options['prefix'] = os.path.join(os.environ['HOME'], '.grass%s' % version[0], 'addons')
        else:
            options['prefix'] = os.environ['GRASS_ADDON_BASE']
    if 'svn.osgeo.org/grass/grass-addons/grass7' in options['svnurl']:
        # use pregenerated modules XML file
        xmlurl = "http://grass.osgeo.org/addons/grass%s" % version[0]
    else:
        # try to get modules XMl from SVN repository
        xmlurl = options['svnurl']

    if not xmlurl.endswith('/'):
        xmlurl = xmlurl + "/"

    # list available extensions
    if flags['l'] or flags['c'] or flags['g']:
        list_available_extensions(xmlurl)
        return 0
    elif flags['a']:
        elist = get_installed_extensions()
        if elist:
            if flags['t']:
                grass.message(_("List of installed extensions (toolboxes):"))
            else:
                grass.message(_("List of installed extensions (modules):"))
            sys.stdout.write('\n'.join(elist))
            sys.stdout.write('\n')
        else:
            if flags['t']:
                grass.info(_("No extension (toolbox) installed"))
            else:
                grass.info(_("No extension (module) installed"))
        return 0
    else:
        if not options['extension']:
            grass.fatal(_('You need to define an extension name or use -l/c/g/a'))

    if flags['d']:
        if options['operation'] != 'add':
            grass.warning(_("Flag 'd' is relevant only to 'operation=add'. Ignoring this flag."))
        else:
            global REMOVE_TMPDIR
            REMOVE_TMPDIR = False

    if options['operation'] == 'add':
        check_dirs()
        install_extension(xmlurl)
    else: # remove
        remove_extension(flags['f'])

    return 0
示例#23
0
def main():
    options, flags = grass.parser()

    # required
    elevation_input = options['elevation']
    aspect_input = options['aspect']
    slope_input = options['slope']

    # optional
    latitude = options['lat']
    longitude = options['long']
    linke_input = options['linke']
    linke_value = options['linke_value']
    albedo_input = options['albedo']
    albedo_value = options['albedo_value']
    horizon_basename = options['horizon_basename']
    horizon_step = options['horizon_step']

    # outputs
    beam_rad = options['beam_rad']
    diff_rad = options['diff_rad']
    refl_rad = options['refl_rad']
    glob_rad = options['glob_rad']
    beam_rad_basename = beam_rad_basename_user = options['beam_rad_basename']
    diff_rad_basename = diff_rad_basename_user = options['diff_rad_basename']
    refl_rad_basename = refl_rad_basename_user = options['refl_rad_basename']
    glob_rad_basename = glob_rad_basename_user = options['glob_rad_basename']

    # missing output?
    if not any([
            beam_rad, diff_rad, refl_rad, glob_rad, beam_rad_basename,
            diff_rad_basename, refl_rad_basename, glob_rad_basename
    ]):
        grass.fatal(_("No output specified."))

    start_day = int(options['start_day'])
    end_day = int(options['end_day'])
    day_step = int(options['day_step'])

    if day_step > 1 and (beam_rad or diff_rad or refl_rad or glob_rad):
        grass.fatal(
            _("Day step higher then 1 would produce"
              " meaningless cumulative maps."))

    # check: start < end
    if start_day > end_day:
        grass.fatal(_("Start day is after end day."))
    if day_step >= end_day - start_day:
        grass.fatal(_("Day step is too big."))

    step = float(options['step'])

    nprocs = int(options['nprocs'])

    solar_constant = float(
        options['solar_constant']) if options['solar_constant'] else None
    if solar_constant:
        # check it's newer version of r.sun
        if not module_has_parameter('r.sun', 'solar_constant'):
            grass.warning(
                _("This version of r.sun lacks solar_constant option, "
                  "it will be ignored. Use newer version of r.sun."))
            solar_constant = None

    if beam_rad and not beam_rad_basename:
        beam_rad_basename = create_tmp_map_name('beam_rad')
        MREMOVE.append(beam_rad_basename)
    if diff_rad and not diff_rad_basename:
        diff_rad_basename = create_tmp_map_name('diff_rad')
        MREMOVE.append(diff_rad_basename)
    if refl_rad and not refl_rad_basename:
        refl_rad_basename = create_tmp_map_name('refl_rad')
        MREMOVE.append(refl_rad_basename)
    if glob_rad and not glob_rad_basename:
        glob_rad_basename = create_tmp_map_name('glob_rad')
        MREMOVE.append(glob_rad_basename)

    # check for existing identical map names
    if not grass.overwrite():
        check_daily_map_names(beam_rad_basename,
                              grass.gisenv()['MAPSET'], start_day, end_day,
                              day_step)
        check_daily_map_names(diff_rad_basename,
                              grass.gisenv()['MAPSET'], start_day, end_day,
                              day_step)
        check_daily_map_names(refl_rad_basename,
                              grass.gisenv()['MAPSET'], start_day, end_day,
                              day_step)
        check_daily_map_names(glob_rad_basename,
                              grass.gisenv()['MAPSET'], start_day, end_day,
                              day_step)

    # check for slope/aspect
    if not aspect_input or not slope_input:
        params = {}
        if not aspect_input:
            aspect_input = create_tmp_map_name('aspect')
            params.update({'aspect': aspect_input})
            REMOVE.append(aspect_input)
        if not slope_input:
            slope_input = create_tmp_map_name('slope')
            params.update({'slope': slope_input})
            REMOVE.append(slope_input)

        grass.info(_("Running r.slope.aspect..."))
        grass.run_command('r.slope.aspect',
                          elevation=elevation_input,
                          quiet=True,
                          **params)

    if beam_rad:
        grass.mapcalc('{beam} = 0'.format(beam=beam_rad), quiet=True)
    if diff_rad:
        grass.mapcalc('{diff} = 0'.format(diff=diff_rad), quiet=True)
    if refl_rad:
        grass.mapcalc('{refl} = 0'.format(refl=refl_rad), quiet=True)
    if glob_rad:
        grass.mapcalc('{glob} = 0'.format(glob=glob_rad), quiet=True)

    rsun_flags = ''
    if flags['m']:
        rsun_flags += 'm'
    if flags['p']:
        rsun_flags += 'p'

    grass.info(_("Running r.sun in a loop..."))
    count = 0
    # Parallel processing
    proc_list = []
    proc_count = 0
    suffixes_all = []
    days = range(start_day, end_day + 1, day_step)
    num_days = len(days)
    core.percent(0, num_days, 1)
    for day in days:
        count += 1
        core.percent(count, num_days, 10)

        suffix = '_' + format_order(day)
        proc_list.append(
            Process(target=run_r_sun,
                    args=(elevation_input, aspect_input, slope_input, latitude,
                          longitude, linke_input, linke_value, albedo_input,
                          albedo_value, horizon_basename, horizon_step,
                          solar_constant, day, step, beam_rad_basename,
                          diff_rad_basename, refl_rad_basename,
                          glob_rad_basename, suffix, rsun_flags)))

        proc_list[proc_count].start()
        proc_count += 1
        suffixes_all.append(suffix)

        if proc_count == nprocs or proc_count == num_days or count == num_days:
            proc_count = 0
            exitcodes = 0
            for proc in proc_list:
                proc.join()
                exitcodes += proc.exitcode

            if exitcodes != 0:
                core.fatal(_("Error while r.sun computation"))

            # Empty process list
            proc_list = []

    if beam_rad:
        sum_maps(beam_rad, beam_rad_basename, suffixes_all)
    if diff_rad:
        sum_maps(diff_rad, diff_rad_basename, suffixes_all)
    if refl_rad:
        sum_maps(refl_rad, refl_rad_basename, suffixes_all)
    if glob_rad:
        sum_maps(glob_rad, glob_rad_basename, suffixes_all)

    # FIXME: how percent really works?
    # core.percent(1, 1, 1)

    # set color table
    if beam_rad:
        set_color_table([beam_rad])
    if diff_rad:
        set_color_table([diff_rad])
    if refl_rad:
        set_color_table([refl_rad])
    if glob_rad:
        set_color_table([glob_rad])

    if not any([
            beam_rad_basename_user, diff_rad_basename_user,
            refl_rad_basename_user, glob_rad_basename_user
    ]):
        return 0

    # add timestamps and register to spatio-temporal raster data set
    temporal = flags['t']
    if temporal:
        core.info(_("Registering created maps into temporal dataset..."))
        import grass.temporal as tgis

        def registerToTemporal(basename, suffixes, mapset, start_day, day_step,
                               title, desc):
            """
            Register daily output maps in spatio-temporal raster data set
            """
            maps = ','.join(
                [basename + suf + '@' + mapset for suf in suffixes])
            tgis.open_new_stds(basename,
                               type='strds',
                               temporaltype='relative',
                               title=title,
                               descr=desc,
                               semantic='sum',
                               dbif=None,
                               overwrite=grass.overwrite())

            tgis.register_maps_in_space_time_dataset(type='rast',
                                                     name=basename,
                                                     maps=maps,
                                                     start=start_day,
                                                     end=None,
                                                     unit='days',
                                                     increment=day_step,
                                                     dbif=None,
                                                     interval=False)

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

        mapset = grass.gisenv()['MAPSET']
        if beam_rad_basename_user:
            registerToTemporal(
                beam_rad_basename,
                suffixes_all,
                mapset,
                start_day,
                day_step,
                title="Beam irradiation",
                desc="Output beam irradiation raster maps [Wh.m-2.day-1]")
        if diff_rad_basename_user:
            registerToTemporal(
                diff_rad_basename,
                suffixes_all,
                mapset,
                start_day,
                day_step,
                title="Diffuse irradiation",
                desc="Output diffuse irradiation raster maps [Wh.m-2.day-1]")
        if refl_rad_basename_user:
            registerToTemporal(
                refl_rad_basename,
                suffixes_all,
                mapset,
                start_day,
                day_step,
                title="Reflected irradiation",
                desc="Output reflected irradiation raster maps [Wh.m-2.day-1]")
        if glob_rad_basename_user:
            registerToTemporal(
                glob_rad_basename,
                suffixes_all,
                mapset,
                start_day,
                day_step,
                title="Total irradiation",
                desc="Output total irradiation raster maps [Wh.m-2.day-1]")

    # just add timestamps, don't register
    else:
        for i, day in enumerate(days):
            if beam_rad_basename_user:
                set_time_stamp(beam_rad_basename + suffixes_all[i], day=day)
            if diff_rad_basename_user:
                set_time_stamp(diff_rad_basename + suffixes_all[i], day=day)
            if refl_rad_basename_user:
                set_time_stamp(refl_rad_basename + suffixes_all[i], day=day)
            if glob_rad_basename_user:
                set_time_stamp(glob_rad_basename + suffixes_all[i], day=day)

    # set color table for daily maps
    if beam_rad_basename_user:
        maps = [beam_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps)
    if diff_rad_basename_user:
        maps = [diff_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps)
    if refl_rad_basename_user:
        maps = [refl_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps)
    if glob_rad_basename_user:
        maps = [glob_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps)
示例#24
0
def draw_linegraph(what):
    yfiles = []

    xfile = os.path.join(tmp_dir, "data_x")

    xf = open(xfile, "w")
    for j, val in enumerate(what[0][3:]):
        xf.write("%d\n" % (j + 1))
    xf.close()

    for i, row in enumerate(what):
        yfile = os.path.join(tmp_dir, "data_y_%d" % i)
        yf = open(yfile, "w")
        for j, val in enumerate(row[3:]):
            yf.write("%s\n" % val)
        yf.close()
        yfiles.append(yfile)

    sienna = "#%02x%02x%02x" % (160, 82, 45)
    coral = "#%02x%02x%02x" % (255, 127, 80)
    gp_colors = ["red", "green", "blue", "magenta", "cyan", sienna, "orange", coral]

    colors = gp_colors
    while len(what) > len(colors):
        colors += gp_colors
    colors = colors[0 : len(what)]

    supported_monitors = ("cairo", "png", "ps")
    monitors = gcore.read_command("d.mon", flags="l", quiet=True)
    found = []
    for monitor in supported_monitors:
        if monitor in monitors:
            found.append(monitor)
    if not found:
        gcore.fatal(
            _(
                "Supported monitor isn't running. Please launch one of the"
                " monitors {}.".format(", ".join(supported_monitors))
            )
        )
    selected_monitor = gcore.read_command("d.mon", flags="p", quiet=True).replace(
        "\n", ""
    )
    if selected_monitor not in supported_monitors:
        gcore.fatal(
            _(
                "Supported monitor isn't selected. Please select one of the"
                " monitors {}.".format(", ".join(supported_monitors))
            )
        )
    with open(gcore.parse_command("d.mon", flags="g", quiet=True)["env"]) as f:
        for line in f.readlines():
            if "GRASS_RENDER_FILE=" in line:
                gcore.info(
                    _(
                        "{} monitor is used, output file {}".format(
                            selected_monitor.capitalize(), line.split("=")[-1]
                        )
                    )
                )
                break

    gcore.run_command(
        "d.linegraph",
        x_file=xfile,
        y_file=yfiles,
        y_color=colors,
        title=_("Spectral signatures"),
        x_title=_("Bands"),
        y_title=_("DN Value"),
    )
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)
示例#26
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)
示例#27
0
def cleanup():
    if len(TMP):
        core.info(_("Cleaning %d temporary maps...") % len(TMP))
    for rast in TMP:
        grass.run_command('g.remove', type='raster', name=rast, flags='f',
                          quiet=True)
示例#28
0
def main():
    options, flags = grass.parser()

    elevation_input = options['elevation']
    aspect_input = options['aspect']
    slope_input = options['slope']
    linke = options['linke']
    linke_value = options['linke_value']
    albedo = options['albedo']
    albedo_value = options['albedo_value']
    coeff_bh = options['coeff_bh']
    coeff_bh_strds = options['coeff_bh_strds']
    coeff_dh = options['coeff_dh']
    coeff_dh_strds = options['coeff_dh_strds']
    lat = options['lat']
    long_ = options['long']

    beam_rad_basename = beam_rad_basename_user = options['beam_rad_basename']
    diff_rad_basename = diff_rad_basename_user = options['diff_rad_basename']
    refl_rad_basename = refl_rad_basename_user = options['refl_rad_basename']
    glob_rad_basename = glob_rad_basename_user = options['glob_rad_basename']
    incidout_basename = options['incidout_basename']

    beam_rad = options['beam_rad']
    diff_rad = options['diff_rad']
    refl_rad = options['refl_rad']
    glob_rad = options['glob_rad']

    has_output = any([
        beam_rad_basename, diff_rad_basename, refl_rad_basename,
        glob_rad_basename, incidout_basename, beam_rad, diff_rad, refl_rad,
        glob_rad
    ])

    if not has_output:
        grass.fatal(_("No output specified."))

    start_time = float(options['start_time'])
    end_time = float(options['end_time'])
    time_step = float(options['time_step'])
    nprocs = int(options['nprocs'])
    day = int(options['day'])
    civil_time = float(
        options['civil_time']) if options['civil_time'] else None
    distance_step = float(
        options['distance_step']) if options['distance_step'] else None
    solar_constant = float(
        options['solar_constant']) if options['solar_constant'] else None
    if solar_constant:
        # check it's newer version of r.sun
        if not module_has_parameter('r.sun', 'solar_constant'):
            grass.warning(
                _("This version of r.sun lacks solar_constant option, "
                  "it will be ignored. Use newer version of r.sun."))
            solar_constant = None
    temporal = flags['t']
    binary = flags['b']
    mode1 = True if options['mode'] == 'mode1' else False
    mode2 = not mode1
    tmpName = 'tmp'
    year = int(options['year'])
    rsun_flags = ''
    if flags['m']:
        rsun_flags += 'm'
    if flags['p']:
        rsun_flags += 'p'

    if not is_grass_7() and temporal:
        grass.warning(_("Flag t has effect only in GRASS 7"))

    # check: start < end
    if start_time > end_time:
        grass.fatal(_("Start time is after end time."))
    if time_step >= end_time - start_time:
        grass.fatal(_("Time step is too big."))

    if mode2 and incidout_basename:
        grass.fatal(_("Can't compute incidence angle in mode 2"))
    if flags['c'] and mode1:
        grass.fatal(
            _("Can't compute cumulative irradiation rasters in mode 1"))
    if mode2 and flags['b']:
        grass.fatal(_("Can't compute binary rasters in mode 2"))
    if any((beam_rad, diff_rad, refl_rad, glob_rad)) and mode1:
        grass.fatal(_("Can't compute irradiation raster maps in mode 1"))

    if beam_rad and not beam_rad_basename:
        beam_rad_basename = create_tmp_map_name('beam_rad')
        MREMOVE.append(beam_rad_basename)
    if diff_rad and not diff_rad_basename:
        diff_rad_basename = create_tmp_map_name('diff_rad')
        MREMOVE.append(diff_rad_basename)
    if refl_rad and not refl_rad_basename:
        refl_rad_basename = create_tmp_map_name('refl_rad')
        MREMOVE.append(refl_rad_basename)
    if glob_rad and not glob_rad_basename:
        glob_rad_basename = create_tmp_map_name('glob_rad')
        MREMOVE.append(glob_rad_basename)

    # here we check all the days
    if not grass.overwrite():
        check_time_map_names(beam_rad_basename,
                             grass.gisenv()['MAPSET'], start_time, end_time,
                             time_step, binary, tmpName, mode1)
        check_time_map_names(diff_rad_basename,
                             grass.gisenv()['MAPSET'], start_time, end_time,
                             time_step, binary, tmpName, mode1)
        check_time_map_names(refl_rad_basename,
                             grass.gisenv()['MAPSET'], start_time, end_time,
                             time_step, binary, tmpName, mode1)
        check_time_map_names(glob_rad_basename,
                             grass.gisenv()['MAPSET'], start_time, end_time,
                             time_step, binary, tmpName, mode1)

    # check for slope/aspect
    if not aspect_input or not slope_input:
        params = {}
        if not aspect_input:
            aspect_input = create_tmp_map_name('aspect')
            params.update({'aspect': aspect_input})
            REMOVE.append(aspect_input)
        if not slope_input:
            slope_input = create_tmp_map_name('slope')
            params.update({'slope': slope_input})
            REMOVE.append(slope_input)

        grass.info(_("Running r.slope.aspect..."))
        grass.run_command('r.slope.aspect',
                          elevation=elevation_input,
                          quiet=True,
                          **params)

    grass.info(_("Running r.sun in a loop..."))
    count = 0
    # Parallel processing
    proc_list = []
    proc_count = 0
    suffixes = []
    suffixes_all = []
    if mode1:
        times = list(frange1(start_time, end_time, time_step))
    else:
        times = list(frange2(start_time, end_time, time_step))
    num_times = len(times)
    core.percent(0, num_times, 1)
    for time in times:
        count += 1
        core.percent(count, num_times, 10)

        coeff_bh_raster = coeff_bh
        if coeff_bh_strds:
            coeff_bh_raster = get_raster_from_strds(year,
                                                    day,
                                                    time,
                                                    strds=coeff_bh_strds)
        coeff_dh_raster = coeff_dh
        if coeff_dh_strds:
            coeff_dh_raster = get_raster_from_strds(year,
                                                    day,
                                                    time,
                                                    strds=coeff_dh_strds)

        suffix = '_' + format_time(time)
        proc_list.append(
            Process(target=run_r_sun,
                    args=(elevation_input, aspect_input, slope_input, day,
                          time, civil_time, linke, linke_value, albedo,
                          albedo_value, coeff_bh_raster, coeff_dh_raster, lat,
                          long_, beam_rad_basename, diff_rad_basename,
                          refl_rad_basename, glob_rad_basename,
                          incidout_basename, suffix, binary, tmpName,
                          None if mode1 else time_step, distance_step,
                          solar_constant, rsun_flags)))

        proc_list[proc_count].start()
        proc_count += 1
        suffixes.append(suffix)
        suffixes_all.append(suffix)

        if proc_count == nprocs or proc_count == num_times or count == num_times:
            proc_count = 0
            exitcodes = 0
            for proc in proc_list:
                proc.join()
                exitcodes += proc.exitcode

            if exitcodes != 0:
                core.fatal(_("Error while r.sun computation"))

            # Empty process list
            proc_list = []
            suffixes = []

    if beam_rad:
        sum_maps(beam_rad, beam_rad_basename, suffixes_all)
        set_color_table([beam_rad])
    if diff_rad:
        sum_maps(diff_rad, diff_rad_basename, suffixes_all)
        set_color_table([diff_rad])
    if refl_rad:
        sum_maps(refl_rad, refl_rad_basename, suffixes_all)
        set_color_table([refl_rad])
    if glob_rad:
        sum_maps(glob_rad, glob_rad_basename, suffixes_all)
        set_color_table([glob_rad])

    if not any([
            beam_rad_basename_user, diff_rad_basename_user,
            refl_rad_basename_user, glob_rad_basename_user
    ]):
        return 0

    # cumulative sum
    if flags['c']:
        copy_tmp = create_tmp_map_name('copy')
        REMOVE.append(copy_tmp)
        for each in (beam_rad_basename_user, diff_rad_basename_user,
                     refl_rad_basename_user, glob_rad_basename_user):
            if each:
                previous = each + suffixes_all[0]
                for suffix in suffixes_all[1:]:
                    new = each + suffix
                    grass.run_command('g.copy',
                                      raster=[new, copy_tmp],
                                      quiet=True)
                    grass.mapcalc("{new} = {previous} + {current}".format(
                        new=new, previous=previous, current=copy_tmp),
                                  overwrite=True)
                    previous = new

    # add timestamps either via temporal framework in 7 or r.timestamp in 6.x
    if is_grass_7() and temporal:
        core.info(_("Registering created maps into temporal dataset..."))
        import grass.temporal as tgis

        def registerToTemporal(basename, suffixes, mapset, start_time,
                               time_step, title, desc):
            maps = ','.join(
                [basename + suf + '@' + mapset for suf in suffixes])
            tgis.open_new_stds(basename,
                               type='strds',
                               temporaltype='absolute',
                               title=title,
                               descr=desc,
                               semantic='mean',
                               dbif=None,
                               overwrite=grass.overwrite())
            tgis.register_maps_in_space_time_dataset(type='raster',
                                                     name=basename,
                                                     maps=maps,
                                                     start=start_time,
                                                     end=None,
                                                     increment=time_step,
                                                     dbif=None,
                                                     interval=False)

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

        mapset = grass.gisenv()['MAPSET']
        if mode2:
            start_time += 0.5 * time_step
        absolute_time = datetime.datetime(year, 1, 1) + \
                        datetime.timedelta(days=day - 1) + \
                        datetime.timedelta(hours=start_time)
        start = absolute_time.strftime("%Y-%m-%d %H:%M:%S")
        step = datetime.timedelta(hours=time_step)
        step = "%d seconds" % step.seconds

        if beam_rad_basename_user:
            registerToTemporal(
                beam_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Beam irradiance" if mode1 else "Beam irradiation",
                desc="Output beam irradiance raster maps [W.m-2]"
                if mode1 else "Output beam irradiation raster maps [Wh.m-2]")
        if diff_rad_basename_user:
            registerToTemporal(
                diff_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Diffuse irradiance" if mode1 else "Diffuse irradiation",
                desc="Output diffuse irradiance raster maps [W.m-2]" if mode1
                else "Output diffuse irradiation raster maps [Wh.m-2]")
        if refl_rad_basename_user:
            registerToTemporal(
                refl_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Reflected irradiance"
                if mode1 else "Reflected irradiation",
                desc="Output reflected irradiance raster maps [W.m-2]" if mode1
                else "Output reflected irradiation raster maps [Wh.m-2]")
        if glob_rad_basename_user:
            registerToTemporal(
                glob_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Total irradiance" if mode1 else "Total irradiation",
                desc="Output total irradiance raster maps [W.m-2]"
                if mode1 else "Output total irradiation raster maps [Wh.m-2]")
        if incidout_basename:
            registerToTemporal(incidout_basename,
                               suffixes_all,
                               mapset,
                               start,
                               step,
                               title="Incidence angle",
                               desc="Output incidence angle raster maps")

    else:
        absolute_time = datetime.datetime(year, 1, 1) + \
                        datetime.timedelta(days=day - 1)
        for i, time in enumerate(times):
            grass_time = format_grass_time(absolute_time +
                                           datetime.timedelta(hours=time))
            if beam_rad_basename_user:
                set_time_stamp(beam_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if diff_rad_basename_user:
                set_time_stamp(diff_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if refl_rad_basename_user:
                set_time_stamp(refl_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if glob_rad_basename_user:
                set_time_stamp(glob_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if incidout_basename:
                set_time_stamp(incidout_basename + suffixes_all[i],
                               time=grass_time)

    if beam_rad_basename_user:
        maps = [beam_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if diff_rad_basename_user:
        maps = [diff_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if refl_rad_basename_user:
        maps = [refl_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if glob_rad_basename_user:
        maps = [glob_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if incidout_basename:
        maps = [incidout_basename + suf for suf in suffixes_all]
        set_color_table(maps)
示例#29
0
文件: r.pdd.py 项目: jsegu/pypdd
def main():
    """main function, called at execution time"""

    # parse arguments
    temp_maps = options['temp'].split(',')
    prec_maps = options['prec'].split(',')
    stdv_maps = options['stdv'].split(',')

    # check that we have compatible number of input maps
    ntemp = len(temp_maps)
    nprec = len(prec_maps)
    nstdv = len(stdv_maps)
    if nprec not in (1, ntemp):
        grass.fatal('Got %i prec maps, expected 1 (constant) or %i (as temp)'
                    % (nprec, ntemp))
    if nstdv not in (1, ntemp):
        grass.fatal('Got %i stdv maps, expected 1 (constant) or %i (as temp)'
                    % (nstdv, ntemp))

    # exit if no output is requested
    out_vars = ['pdd', 'accu', 'snow_melt', 'ice_melt', 'melt', 'runoff', 'smb']
    out_maps = {var: options[var] for var in out_vars if options[var] != ''}
    if len(out_maps) == 0:
        grass.fatal('No output required. Please inform at least one of ' +
                    ', '.join(out_vars) + '.')

    # read temperature maps
    grass.info('reading temperature maps...')
    temp = [garray.array() for m in temp_maps]
    for i, m in enumerate(temp_maps):
        temp[i].read(m)
        grass.percent(i, ntemp, 1)
    temp = np.asarray(temp)

    # read precipitation maps
    grass.info('reading precipitation maps...')
    prec = [garray.array() for m in temp_maps]
    for i, m in enumerate(prec_maps):
        prec[i].read(m)
        grass.percent(i, nprec, 1)
    prec = np.asarray(prec)

    # read standard deviation maps
    if stdv_maps != ['']:
        grass.info('reading standard deviation maps...')
        stdv = [garray.array() for m in stdv_maps]
        for i, m in enumerate(stdv_maps):
            stdv[i].read(m)
            grass.percent(i, nstdv, 1)
        stdv = np.asarray(stdv)
    else:
        stdv = 0.0

    # initialize PDD model
    pdd = PDDModel()
    for param in ('pdd_factor_snow', 'pdd_factor_ice',
                  'refreeze_snow', 'refreeze_ice', 'temp_snow', 'temp_rain',
                  'interpolate_rule', 'interpolate_n'):
        if options[param]:
            setattr(pdd, param, float(options[param]))
    for param in ('interpolate_rule',):
        if options[param]:
            setattr(pdd, param, str(options[param]))

    # run PDD model
    grass.info('running PDD model...')
    smb = pdd(temp, prec, stdv)

    # write output maps
    grass.info('writing output maps...')
    for varname in ['pdd', 'accu', 'snow_melt', 'ice_melt', 'melt',
                    'runoff', 'smb']:
        if options[varname]:
            a = garray.array()
            a[:] = smb[varname]
            a.write(mapname=options[varname])
示例#30
0
def main():
    """main function, called at execution time"""

    # parse arguments
    temp_maps = options['temp'].split(',')
    prec_maps = options['prec'].split(',')
    stdv_maps = options['stdv'].split(',')

    # check that we have compatible number of input maps
    ntemp = len(temp_maps)
    nprec = len(prec_maps)
    nstdv = len(stdv_maps)
    if nprec not in (1, ntemp):
        grass.fatal('Got %i prec maps, expected 1 (constant) or %i (as temp)' %
                    (nprec, ntemp))
    if nstdv not in (1, ntemp):
        grass.fatal('Got %i stdv maps, expected 1 (constant) or %i (as temp)' %
                    (nstdv, ntemp))

    # exit if no output is requested
    out_vars = [
        'pdd', 'accu', 'snow_melt', 'ice_melt', 'melt', 'runoff', 'smb'
    ]
    out_maps = {var: options[var] for var in out_vars if options[var] != ''}
    if len(out_maps) == 0:
        grass.fatal('No output required. Please inform at least one of ' +
                    ', '.join(out_vars) + '.')

    # read temperature maps
    grass.info('reading temperature maps...')
    temp = [garray.array() for m in temp_maps]
    for i, m in enumerate(temp_maps):
        temp[i].read(m)
        grass.percent(i, ntemp, 1)
    temp = np.asarray(temp)

    # read precipitation maps
    grass.info('reading precipitation maps...')
    prec = [garray.array() for m in temp_maps]
    for i, m in enumerate(prec_maps):
        prec[i].read(m)
        grass.percent(i, nprec, 1)
    prec = np.asarray(prec)

    # read standard deviation maps
    if stdv_maps != ['']:
        grass.info('reading standard deviation maps...')
        stdv = [garray.array() for m in stdv_maps]
        for i, m in enumerate(stdv_maps):
            stdv[i].read(m)
            grass.percent(i, nstdv, 1)
        stdv = np.asarray(stdv)
    else:
        stdv = 0.0

    # initialize PDD model
    pdd = PDDModel()
    for param in ('pdd_factor_snow', 'pdd_factor_ice', 'refreeze_snow',
                  'refreeze_ice', 'temp_snow', 'temp_rain', 'interpolate_rule',
                  'interpolate_n'):
        if options[param]:
            setattr(pdd, param, float(options[param]))
    for param in ('interpolate_rule', ):
        if options[param]:
            setattr(pdd, param, str(options[param]))

    # run PDD model
    grass.info('running PDD model...')
    smb = pdd(temp, prec, stdv)

    # write output maps
    grass.info('writing output maps...')
    for varname in [
            'pdd', 'accu', 'snow_melt', 'ice_melt', 'melt', 'runoff', 'smb'
    ]:
        if options[varname]:
            a = garray.array()
            a[:] = smb[varname]
            a.write(mapname=options[varname])
示例#31
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) > 1 and argv[1] == "-d":
        printDiff = True
    else:
        printDiff = False

    if len(argv) > 1 and argv[1] == "-h":
        print(sys.stderr, __doc__, file=sys.stderr)
        return 1

    nuldev = open(os.devnull, "w+")
    grass.info("Step 1: running make...")
    grass.call(["make"], stderr=nuldev)
    grass.info("Step 2: parsing modules...")
    modules = dict()
    modules = parseModules()
    grass.info("Step 3: reading menu data...")
    data = LayerManagerMenuData()
    grass.info("Step 4: updating menu data...")
    updateData(data, modules)

    if printDiff:
        tempFile = tempfile.NamedTemporaryFile()
        grass.info("Step 5: diff menu data...")
        writeData(data, tempFile.name)

        grass.call(
            ["diff", "-u",
             os.path.join("xml", "menudata.xml"), tempFile.name],
            stderr=nuldev,
        )
    else:
        grass.info("Step 5: writing menu data (menudata.xml)...")
        writeData(data)

    return 0
示例#32
0
def main():
    options, flags = gcore.parser()

    elevation = options["elevation"]
    strds = options["output"]
    basename = strds
    start_water_level = float(options["start_water_level"])
    end_water_level = float(options["end_water_level"])
    water_level_step = float(options["water_level_step"])
    # if options['coordinates']:
    #    options['coordinates'].split(',')
    # passing coordinates parameter as is
    coordinates = options["coordinates"]
    seed_raster = options["seed_raster"]
    if seed_raster and coordinates:
        gcore.fatal(
            _("Both seed raster and coordinates cannot be specified"
              " together, please specify only one of them."))

    time_unit = options["time_unit"]
    time_step = options[
        "time_step"]  # temporal fucntions accepts only string now
    if int(time_step) <= 0:
        gcore.fatal(
            _("Time step must be greater than zero."
              " Please specify number > 0."))

    mapset = gcore.gisenv()["MAPSET"]
    title = _("r.lake series")
    desctiption = _("r.lake series")

    water_levels = [
        step for step in frange(start_water_level, end_water_level,
                                water_level_step)
    ]
    outputs = [
        "%s%s%s" % (basename, "_", water_level) for water_level in water_levels
    ]

    if not gcore.overwrite():
        check_maps_exist(outputs, mapset)

    kwargs = {}
    if seed_raster:
        kwargs["seed"] = seed_raster
    elif coordinates:
        kwargs["coordinates"] = coordinates

    if flags["n"]:
        pass_flags = "n"
    else:
        pass_flags = None

    for i, water_level in enumerate(water_levels):
        try:
            gcore.run_command(
                "r.lake",
                flags=pass_flags,
                elevation=elevation,
                lake=outputs[i],
                water_level=water_level,
                overwrite=gcore.overwrite(
                ),  # TODO: really works? Its seems that hardcoding here False does not prevent overwriting.
                **kwargs)
        except CalledModuleError:
            # remove maps created so far, try to remove also i-th map
            remove_raster_maps(outputs[:i], quiet=True)
            gcore.fatal(
                _("r.lake command failed. Check above error messages."
                  " Try different water levels or seed points."))
    gcore.info(_("Registering created maps into temporal dataset..."))

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

    tgis.open_new_stds(
        strds,
        type="strds",
        temporaltype="relative",
        title=title,
        descr=desctiption,
        semantic="sum",
        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="raster",
        name=basename,
        maps=",".join(outputs),
        start=str(1),
        end=None,
        unit=time_unit,
        increment=time_step,
        interval=False,
        dbif=None,
    )
示例#33
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) > 1 and argv[1] == '-d':
        printDiff = True
    else:
        printDiff = False

    if len(argv) > 1 and argv[1] == '-h':
        print >> sys.stderr, __doc__
        return 1

    nuldev = file(os.devnull, 'w+')
    grass.info("Step 1: running make...")
    grass.call(['make'], stderr=nuldev)
    grass.info("Step 2: parsing modules...")
    modules = dict()
    modules = parseModules()
    grass.info("Step 3: reading menu data...")
    data = LayerManagerMenuData()
    grass.info("Step 4: updating menu data...")
    updateData(data, modules)

    if printDiff:
        tempFile = tempfile.NamedTemporaryFile()
        grass.info("Step 5: diff menu data...")
        writeData(data, tempFile.name)

        grass.call(['diff', '-u',
                    os.path.join('xml', 'menudata.xml'),
                    tempFile.name], stderr=nuldev)
    else:
        grass.info("Step 5: writing menu data (menudata.xml)...")
        writeData(data)

    return 0
示例#34
0
def main():
    options, flags = grass.parser()

    elevation_input = options['elevation']
    aspect_input = options['aspect']
    slope_input = options['slope']
                      
    linke = options['linke']
    linke_value = options['linke_value']
    albedo = options['albedo']
    albedo_value = options['albedo_value']
    horizon_basename = options['horizon_basename']
    horizon_step = options['horizon_step']

    beam_rad_basename = options['beam_rad_basename']
    diff_rad_basename = options['diff_rad_basename']
    refl_rad_basename = options['refl_rad_basename']
    glob_rad_basename = options['glob_rad_basename']
    incidout_basename = options['incidout_basename']

    if not any([beam_rad_basename, diff_rad_basename,
                refl_rad_basename, glob_rad_basename,
                incidout_basename]):
        grass.fatal(_("No output specified."))

    start_time = float(options['start_time'])
    end_time = float(options['end_time'])
    time_step = float(options['time_step'])
    nprocs = int(options['nprocs'])
    day = int(options['day'])
    temporal = flags['t']
    binary = flags['b']
    binaryTmpName = 'binary'
    year = int(options['year'])
   
    

    if not is_grass_7() and temporal:
        grass.warning(_("Flag t has effect only in GRASS 7"))

    # check: start < end
    if start_time > end_time:
        grass.fatal(_("Start time is after end time."))
    if time_step >= end_time - start_time:
        grass.fatal(_("Time step is too big."))

    # here we check all the days
    if not grass.overwrite():
        check_time_map_names(beam_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)
        check_time_map_names(diff_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)
        check_time_map_names(refl_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)
        check_time_map_names(glob_rad_basename, grass.gisenv()['MAPSET'],
                             start_time, end_time, time_step, binary,
                             binaryTmpName)

    # check for slope/aspect
    if not aspect_input or not slope_input:
        params = {}
        if not aspect_input:
            aspect_input = create_tmp_map_name('aspect')
            params.update({'aspect': aspect_input})
            TMP.append(aspect_input)
        if not slope_input:
            slope_input = create_tmp_map_name('slope')
            params.update({'slope': slope_input})
            TMP.append(slope_input)

        grass.info(_("Running r.slope.aspect..."))
        grass.run_command('r.slope.aspect', elevation=elevation_input,
                          quiet=True, **params)

    grass.info(_("Running r.sun in a loop..."))
    count = 0
    # Parallel processing
    proc_list = []
    proc_count = 0
    suffixes = []
    suffixes_all = []
    times = list(frange(start_time, end_time, time_step))
    num_times = len(times)
    core.percent(0, num_times, 1)
    for time in times:
        count += 1
        core.percent(count, num_times, 10)

        suffix = '_' + format_time(time)
        proc_list.append(Process(target=run_r_sun,
                                 args=(elevation_input, aspect_input,
                                       slope_input, day, time,
                                       linke, linke_value,
                                       albedo, albedo_value,
                                       horizon_basename, horizon_step,
                                       beam_rad_basename,
                                       diff_rad_basename,
                                       refl_rad_basename,
                                       glob_rad_basename,                                     
                                       incidout_basename,
                                       suffix,
                                       binary, binaryTmpName)))

        proc_list[proc_count].start()
        proc_count += 1
        suffixes.append(suffix)
        suffixes_all.append(suffix)

        if proc_count == nprocs or proc_count == num_times or count == num_times:
            proc_count = 0
            exitcodes = 0
            for proc in proc_list:
                proc.join()
                exitcodes += proc.exitcode

            if exitcodes != 0:
                core.fatal(_("Error while r.sun computation"))

            # Empty process list
            proc_list = []
            suffixes = []
    # FIXME: how percent really works?
    # core.percent(1, 1, 1)

    # add timestamps either via temporal framework in 7 or r.timestamp in 6.x
    if is_grass_7() and temporal:
        core.info(_("Registering created maps into temporal dataset..."))
        import grass.temporal as tgis

        def registerToTemporal(basename, suffixes, mapset, start_time,
                               time_step, title, desc):
            maps = ','.join([basename + suf + '@' + mapset for suf in suffixes])
            tgis.open_new_stds(basename, type='strds',
                               temporaltype='absolute',
                               title=title, descr=desc,
                               semantic='mean', dbif=None,
                               overwrite=grass.overwrite())
            tgis.register_maps_in_space_time_dataset(
                type='raster', name=basename, maps=maps, start=start_time,
                end=None, increment=time_step, dbif=None, interval=False)
        # Make sure the temporal database exists
        tgis.init()

        mapset = grass.gisenv()['MAPSET']
        absolute_time = datetime.datetime(year, 1, 1) + \
                        datetime.timedelta(days=day - 1) + \
                        datetime.timedelta(hours=start_time)
        start = absolute_time.strftime("%Y-%m-%d %H:%M:%S")
        step = datetime.timedelta(hours=time_step)
        step = "%d seconds" % step.seconds

        if beam_rad_basename:
            registerToTemporal(beam_rad_basename, suffixes_all, mapset, start,
                               step, title="Beam irradiance",
                               desc="Output beam irradiance raster maps [Wh.m-2]")
        if diff_rad_basename:
            registerToTemporal(diff_rad_basename, suffixes_all, mapset, start,
                               step, title="Diffuse irradiance",
                               desc="Output diffuse irradiance raster maps [Wh.m-2]")
        if refl_rad_basename:
            registerToTemporal(refl_rad_basename, suffixes_all, mapset, start,
                               step, title="Reflected irradiance",
                               desc="Output reflected irradiance raster maps [Wh.m-2]")
        if glob_rad_basename:
            registerToTemporal(glob_rad_basename, suffixes_all, mapset, start,
                               step, title="Total irradiance",
                               desc="Output total irradiance raster maps [Wh.m-2]")
        if incidout_basename:
            registerToTemporal(incidout_basename, suffixes_all, mapset, start,
                               step, title="Incidence angle",
                               desc="Output incidence angle raster maps")

    else:
        absolute_time = datetime.datetime(year, 1, 1) + \
                        datetime.timedelta(days=day - 1)
        for i, time in enumerate(times):
            grass_time = format_grass_time(absolute_time + datetime.timedelta(hours=time))
            if beam_rad_basename:
                set_time_stamp(beam_rad_basename + suffixes_all[i],
                               time=grass_time)
            if diff_rad_basename:
                set_time_stamp(diff_rad_basename + suffixes_all[i],
                               time=grass_time)
            if refl_rad_basename:
                set_time_stamp(refl_rad_basename + suffixes_all[i],
                               time=grass_time)
            if glob_rad_basename:
                set_time_stamp(glob_rad_basename + suffixes_all[i],
                               time=grass_time)
            if incidout_basename:
                set_time_stamp(incidout_basename + suffixes_all[i],
                               time=grass_time)

    if beam_rad_basename:
        maps = [beam_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if diff_rad_basename:
        maps = [diff_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if refl_rad_basename:
        maps = [refl_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if glob_rad_basename:
        maps = [glob_rad_basename + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if incidout_basename:
        maps = [incidout_basename + suf for suf in suffixes_all]
        set_color_table(maps)
示例#35
0
def main():
    developments = options['development'].split(',')
    observed_popul_file = options['observed_population']
    projected_popul_file = options['projected_population']
    sep = gutils.separator(options['separator'])
    subregions = options['subregions']
    methods = options['method'].split(',')
    plot = options['plot']
    simulation_times = [
        float(each) for each in options['simulation_times'].split(',')
    ]

    for each in methods:
        if each in ('exp_approach', 'logarithmic2'):
            try:
                from scipy.optimize import curve_fit
            except ImportError:
                gcore.fatal(
                    _("Importing scipy failed. Method '{m}' is not available").
                    format(m=each))

    # exp approach needs at least 3 data points
    if len(developments) <= 2 and ('exp_approach' in methods
                                   or 'logarithmic2' in methods):
        gcore.fatal(_("Not enough data for method 'exp_approach'"))
    if len(developments) == 3 and ('exp_approach' in methods
                                   and 'logarithmic2' in methods):
        gcore.warning(
            _("Can't decide between 'exp_approach' and 'logarithmic2' methods"
              " because both methods can have exact solutions for 3 data points resulting in RMSE = 0"
              ))
    observed_popul = np.genfromtxt(observed_popul_file,
                                   dtype=float,
                                   delimiter=sep,
                                   names=True)
    projected_popul = np.genfromtxt(projected_popul_file,
                                    dtype=float,
                                    delimiter=sep,
                                    names=True)
    year_col = observed_popul.dtype.names[0]
    observed_times = observed_popul[year_col]
    year_col = projected_popul.dtype.names[0]
    projected_times = projected_popul[year_col]

    if len(developments) != len(observed_times):
        gcore.fatal(
            _("Number of development raster maps doesn't not correspond to the number of observed times"
              ))

    # gather developed cells in subregions
    gcore.info(_("Computing number of developed cells..."))
    table_developed = {}
    subregionIds = set()
    for i in range(len(observed_times)):
        gcore.percent(i, len(observed_times), 1)
        data = gcore.read_command('r.univar',
                                  flags='gt',
                                  zones=subregions,
                                  map=developments[i])
        for line in data.splitlines():
            stats = line.split('|')
            if stats[0] == 'zone':
                continue
            subregionId, developed_cells = stats[0], int(stats[12])
            subregionIds.add(subregionId)
            if i == 0:
                table_developed[subregionId] = []
            table_developed[subregionId].append(developed_cells)
        gcore.percent(1, 1, 1)
    subregionIds = sorted(list(subregionIds))
    # linear interpolation between population points
    population_for_simulated_times = {}
    for subregionId in table_developed.keys():
        population_for_simulated_times[subregionId] = np.interp(
            x=simulation_times,
            xp=np.append(observed_times, projected_times),
            fp=np.append(observed_popul[subregionId],
                         projected_popul[subregionId]))
    # regression
    demand = {}
    i = 0
    if plot:
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        n_plots = np.ceil(np.sqrt(len(subregionIds)))
        fig = plt.figure(figsize=(5 * n_plots, 5 * n_plots))

    for subregionId in subregionIds:
        i += 1
        rmse = dict()
        predicted = dict()
        simulated = dict()
        coeff = dict()
        for method in methods:
            # observed population points for subregion
            reg_pop = observed_popul[subregionId]
            simulated[method] = np.array(
                population_for_simulated_times[subregionId])

            if method in ('exp_approach', 'logarithmic2'):
                # we have to scale it first
                y = np.array(table_developed[subregionId])
                magn = float(
                    np.power(
                        10,
                        max(magnitude(np.max(reg_pop)), magnitude(np.max(y)))))
                x = reg_pop / magn
                y = y / magn
                if method == 'exp_approach':
                    initial = (
                        0.5, np.mean(x), np.mean(y)
                    )  # this seems to work best for our data for exp_approach
                elif method == 'logarithmic2':
                    popt, pcov = curve_fit(logarithmic, x, y)
                    initial = (popt[0], popt[1], 0)
                with np.errstate(
                        invalid='warn'
                ):  # when 'raise' it stops every time on FloatingPointError
                    try:
                        popt, pcov = curve_fit(globals()[method],
                                               x,
                                               y,
                                               p0=initial)
                        if np.isnan(popt).any():
                            raise RuntimeError
                        # would result in nans in predicted
                        if method == 'logarithmic2' and np.any(
                                simulated[method] / magn <= popt[-1]):
                            raise RuntimeError
                    except (FloatingPointError, RuntimeError):
                        rmse[
                            method] = sys.maxsize  # so that other method is selected
                        gcore.warning(
                            _("Method '{m}' cannot converge for subregion {reg}"
                              .format(m=method, reg=subregionId)))
                        if len(methods) == 1:
                            gcore.fatal(
                                _("Method '{m}' failed for subregion {reg},"
                                  " please select at least one other method").
                                format(m=method, reg=subregionId))
                    else:
                        predicted[method] = globals()[method](
                            simulated[method] / magn, *popt) * magn
                        r = globals()[method](
                            x, *popt) * magn - table_developed[subregionId]
                        coeff[method] = popt
                        if len(reg_pop) > 3:
                            rmse[method] = np.sqrt(
                                (np.sum(r * r) / (len(reg_pop) - 3)))
                        else:
                            rmse[method] = 0
            else:
                if method == 'logarithmic':
                    reg_pop = np.log(reg_pop)
                if method == 'exponential':
                    y = np.log(table_developed[subregionId])
                else:
                    y = table_developed[subregionId]
                A = np.vstack((reg_pop, np.ones(len(reg_pop)))).T
                npversion = [int(x) for x in np.__version__.split('.')]
                if npversion >= [1, 14, 0]:
                    rcond = None
                else:
                    rcond = -1
                m, c = np.linalg.lstsq(A, y, rcond=rcond)[0]  # y = mx + c
                coeff[method] = m, c

                if method == 'logarithmic':
                    with np.errstate(invalid='ignore', divide='ignore'):
                        predicted[method] = np.where(
                            simulated[method] > 1,
                            np.log(simulated[method]) * m + c, 0)
                    predicted[method] = np.where(predicted[method] > 0,
                                                 predicted[method], 0)
                    r = (reg_pop * m + c) - table_developed[subregionId]
                elif method == 'exponential':
                    predicted[method] = np.exp(m * simulated[method] + c)
                    r = np.exp(m * reg_pop + c) - table_developed[subregionId]
                else:  # linear
                    predicted[method] = simulated[method] * m + c
                    r = (reg_pop * m + c) - table_developed[subregionId]
                # RMSE
                if len(reg_pop) > 2:
                    rmse[method] = np.sqrt(
                        (np.sum(r * r) / (len(reg_pop) - 2)))
                else:
                    rmse[method] = 0

        method = min(rmse, key=rmse.get)
        gcore.verbose(
            _("Method '{meth}' was selected for subregion {reg}").format(
                meth=method, reg=subregionId))
        # write demand
        demand[subregionId] = predicted[method]
        demand[subregionId] = np.diff(demand[subregionId])
        if np.any(demand[subregionId] < 0):
            gcore.warning(
                _("Subregion {sub} has negative numbers"
                  " of newly developed cells, changing to zero".format(
                      sub=subregionId)))
            demand[subregionId][demand[subregionId] < 0] = 0
        if coeff[method][0] < 0:
            # couldn't establish reliable population-area
            # project by number of developed pixels in analyzed period
            range_developed = table_developed[subregionId][
                -1] - table_developed[subregionId][0]
            range_times = observed_times[-1] - observed_times[0]
            dev_per_step = math.ceil(range_developed / float(range_times))
            # this assumes demand is projected yearly
            demand[subregionId].fill(dev_per_step if dev_per_step > 0 else 0)
            gcore.warning(
                _("For subregion {sub} population and development are inversely proportional,"
                  " demand will be interpolated based on prior change in development only."
                  .format(sub=subregionId)))

        # draw
        if plot:
            ax = fig.add_subplot(n_plots, n_plots, i)
            ax.set_title("{sid}, RMSE: {rmse:.3f}".format(sid=subregionId,
                                                          rmse=rmse[method]))
            ax.set_xlabel('population')
            ax.set_ylabel('developed cells')
            # plot known points
            x = np.array(observed_popul[subregionId])
            y = np.array(table_developed[subregionId])
            ax.plot(x, y, marker='o', linestyle='', markersize=8)
            # plot predicted curve
            x_pred = np.linspace(
                np.min(x),
                np.max(np.array(population_for_simulated_times[subregionId])),
                30)
            cf = coeff[method]
            if method == 'linear':
                line = x_pred * cf[0] + cf[1]
                label = "$y = {c:.3f} + {m:.3f} x$".format(m=cf[0], c=cf[1])
            elif method == 'logarithmic':
                line = np.log(x_pred) * cf[0] + cf[1]
                label = "$y = {c:.3f} + {m:.3f} \ln(x)$".format(m=cf[0],
                                                                c=cf[1])
            elif method == 'exponential':
                line = np.exp(x_pred * cf[0] + cf[1])
                label = "$y = {c:.3f} e^{{{m:.3f}x}}$".format(m=cf[0],
                                                              c=np.exp(cf[1]))
            elif method == 'exp_approach':
                line = exp_approach(x_pred / magn, *cf) * magn
                label = "$y = (1 -  e^{{-{A:.3f}(x-{B:.3f})}}) + {C:.3f}$".format(
                    A=cf[0], B=cf[1], C=cf[2])
            elif method == 'logarithmic2':
                line = logarithmic2(x_pred / magn, *cf) * magn
                label = "$y = {A:.3f} + {B:.3f} \ln(x-{C:.3f})$".format(
                    A=cf[0], B=cf[1], C=cf[2])

            ax.plot(x_pred, line, label=label)
            ax.plot(simulated[method],
                    predicted[method],
                    linestyle='',
                    marker='o',
                    markerfacecolor='None')
            plt.legend(loc=0)
            labels = ax.get_xticklabels()
            plt.setp(labels, rotation=30)
    if plot:
        plt.tight_layout()
        fig.savefig(plot)

    # write demand
    with open(options['demand'], 'w') as f:
        header = observed_popul.dtype.names  # the order is kept here
        header = [header[0]
                  ] + [sub for sub in header[1:] if sub in subregionIds]
        f.write(sep.join(header))
        f.write('\n')
        i = 0
        for time in simulation_times[1:]:
            f.write(str(int(time)))
            f.write(sep)
            # put 0 where there are more counties but are not in region
            for sub in header[1:]:  # to keep order of subregions
                f.write(str(int(demand[sub][i])))
                if sub != header[-1]:
                    f.write(sep)
            f.write('\n')
            i += 1
示例#36
0
def main():
    options, flags = grass.parser()

    elevation_input = options["elevation"]
    aspect_input = options["aspect"]
    slope_input = options["slope"]
    linke = options["linke"]
    linke_value = options["linke_value"]
    albedo = options["albedo"]
    albedo_value = options["albedo_value"]
    coeff_bh = options["coeff_bh"]
    coeff_bh_strds = options["coeff_bh_strds"]
    coeff_dh = options["coeff_dh"]
    coeff_dh_strds = options["coeff_dh_strds"]
    lat = options["lat"]
    long_ = options["long"]

    beam_rad_basename = beam_rad_basename_user = options["beam_rad_basename"]
    diff_rad_basename = diff_rad_basename_user = options["diff_rad_basename"]
    refl_rad_basename = refl_rad_basename_user = options["refl_rad_basename"]
    glob_rad_basename = glob_rad_basename_user = options["glob_rad_basename"]
    incidout_basename = options["incidout_basename"]

    beam_rad = options["beam_rad"]
    diff_rad = options["diff_rad"]
    refl_rad = options["refl_rad"]
    glob_rad = options["glob_rad"]

    has_output = any([
        beam_rad_basename,
        diff_rad_basename,
        refl_rad_basename,
        glob_rad_basename,
        incidout_basename,
        beam_rad,
        diff_rad,
        refl_rad,
        glob_rad,
    ])

    if not has_output:
        grass.fatal(_("No output specified."))

    start_time = float(options["start_time"])
    end_time = float(options["end_time"])
    time_step = float(options["time_step"])
    nprocs = int(options["nprocs"])
    day = int(options["day"])
    civil_time = float(
        options["civil_time"]) if options["civil_time"] else None
    distance_step = (float(options["distance_step"])
                     if options["distance_step"] else None)
    solar_constant = (float(options["solar_constant"])
                      if options["solar_constant"] else None)
    temporal = flags["t"]
    binary = flags["b"]
    mode1 = True if options["mode"] == "mode1" else False
    mode2 = not mode1
    tmpName = "tmp"
    year = int(options["year"])
    rsun_flags = ""
    if flags["m"]:
        rsun_flags += "m"
    if flags["p"]:
        rsun_flags += "p"

    # check: start < end
    if start_time > end_time:
        grass.fatal(_("Start time is after end time."))
    if time_step >= end_time - start_time:
        grass.fatal(_("Time step is too big."))

    if mode2 and incidout_basename:
        grass.fatal(_("Can't compute incidence angle in mode 2"))
    if flags["c"] and mode1:
        grass.fatal(
            _("Can't compute cumulative irradiation rasters in mode 1"))
    if mode2 and flags["b"]:
        grass.fatal(_("Can't compute binary rasters in mode 2"))
    if any((beam_rad, diff_rad, refl_rad, glob_rad)) and mode1:
        grass.fatal(_("Can't compute irradiation raster maps in mode 1"))

    if beam_rad and not beam_rad_basename:
        beam_rad_basename = create_tmp_map_name("beam_rad")
        MREMOVE.append(beam_rad_basename)
    if diff_rad and not diff_rad_basename:
        diff_rad_basename = create_tmp_map_name("diff_rad")
        MREMOVE.append(diff_rad_basename)
    if refl_rad and not refl_rad_basename:
        refl_rad_basename = create_tmp_map_name("refl_rad")
        MREMOVE.append(refl_rad_basename)
    if glob_rad and not glob_rad_basename:
        glob_rad_basename = create_tmp_map_name("glob_rad")
        MREMOVE.append(glob_rad_basename)

    # here we check all the days
    if not grass.overwrite():
        check_time_map_names(
            beam_rad_basename,
            grass.gisenv()["MAPSET"],
            start_time,
            end_time,
            time_step,
            binary,
            tmpName,
            mode1,
        )
        check_time_map_names(
            diff_rad_basename,
            grass.gisenv()["MAPSET"],
            start_time,
            end_time,
            time_step,
            binary,
            tmpName,
            mode1,
        )
        check_time_map_names(
            refl_rad_basename,
            grass.gisenv()["MAPSET"],
            start_time,
            end_time,
            time_step,
            binary,
            tmpName,
            mode1,
        )
        check_time_map_names(
            glob_rad_basename,
            grass.gisenv()["MAPSET"],
            start_time,
            end_time,
            time_step,
            binary,
            tmpName,
            mode1,
        )

    # check for slope/aspect
    if not aspect_input or not slope_input:
        params = {}
        if not aspect_input:
            aspect_input = create_tmp_map_name("aspect")
            params.update({"aspect": aspect_input})
            REMOVE.append(aspect_input)
        if not slope_input:
            slope_input = create_tmp_map_name("slope")
            params.update({"slope": slope_input})
            REMOVE.append(slope_input)

        grass.info(_("Running r.slope.aspect..."))
        grass.run_command("r.slope.aspect",
                          elevation=elevation_input,
                          quiet=True,
                          **params)

    grass.info(_("Running r.sun in a loop..."))
    count = 0
    # Parallel processing
    proc_list = []
    proc_count = 0
    suffixes = []
    suffixes_all = []
    if mode1:
        times = list(frange1(start_time, end_time, time_step))
    else:
        times = list(frange2(start_time, end_time, time_step))
    num_times = len(times)
    core.percent(0, num_times, 1)
    for time in times:
        count += 1
        core.percent(count, num_times, 10)

        coeff_bh_raster = coeff_bh
        if coeff_bh_strds:
            coeff_bh_raster = get_raster_from_strds(year,
                                                    day,
                                                    time,
                                                    strds=coeff_bh_strds)
        coeff_dh_raster = coeff_dh
        if coeff_dh_strds:
            coeff_dh_raster = get_raster_from_strds(year,
                                                    day,
                                                    time,
                                                    strds=coeff_dh_strds)

        suffix = "_" + format_time(time)
        proc_list.append(
            Process(
                target=run_r_sun,
                args=(
                    elevation_input,
                    aspect_input,
                    slope_input,
                    day,
                    time,
                    civil_time,
                    linke,
                    linke_value,
                    albedo,
                    albedo_value,
                    coeff_bh_raster,
                    coeff_dh_raster,
                    lat,
                    long_,
                    beam_rad_basename,
                    diff_rad_basename,
                    refl_rad_basename,
                    glob_rad_basename,
                    incidout_basename,
                    suffix,
                    binary,
                    tmpName,
                    None if mode1 else time_step,
                    distance_step,
                    solar_constant,
                    rsun_flags,
                ),
            ))

        proc_list[proc_count].start()
        proc_count += 1
        suffixes.append(suffix)
        suffixes_all.append(suffix)

        if proc_count == nprocs or proc_count == num_times or count == num_times:
            proc_count = 0
            exitcodes = 0
            for proc in proc_list:
                proc.join()
                exitcodes += proc.exitcode

            if exitcodes != 0:
                core.fatal(_("Error while r.sun computation"))

            # Empty process list
            proc_list = []
            suffixes = []

    if beam_rad:
        sum_maps(beam_rad, beam_rad_basename, suffixes_all)
        set_color_table([beam_rad])
    if diff_rad:
        sum_maps(diff_rad, diff_rad_basename, suffixes_all)
        set_color_table([diff_rad])
    if refl_rad:
        sum_maps(refl_rad, refl_rad_basename, suffixes_all)
        set_color_table([refl_rad])
    if glob_rad:
        sum_maps(glob_rad, glob_rad_basename, suffixes_all)
        set_color_table([glob_rad])

    if not any([
            beam_rad_basename_user,
            diff_rad_basename_user,
            refl_rad_basename_user,
            glob_rad_basename_user,
    ]):
        return 0

    # cumulative sum
    if flags["c"]:
        copy_tmp = create_tmp_map_name("copy")
        REMOVE.append(copy_tmp)
        for each in (
                beam_rad_basename_user,
                diff_rad_basename_user,
                refl_rad_basename_user,
                glob_rad_basename_user,
        ):
            if each:
                previous = each + suffixes_all[0]
                for suffix in suffixes_all[1:]:
                    new = each + suffix
                    grass.run_command("g.copy",
                                      raster=[new, copy_tmp],
                                      quiet=True)
                    grass.mapcalc(
                        "{new} = {previous} + {current}".format(
                            new=new, previous=previous, current=copy_tmp),
                        overwrite=True,
                    )
                    previous = new

    # add to temporal framework
    if temporal:
        core.info(_("Registering created maps into temporal dataset..."))
        import grass.temporal as tgis

        def registerToTemporal(basename, suffixes, mapset, start_time,
                               time_step, title, desc):
            maps = ",".join(
                [basename + suf + "@" + mapset for suf in suffixes])
            tgis.open_new_stds(
                basename,
                type="strds",
                temporaltype="absolute",
                title=title,
                descr=desc,
                semantic="mean",
                dbif=None,
                overwrite=grass.overwrite(),
            )
            tgis.register_maps_in_space_time_dataset(
                type="raster",
                name=basename,
                maps=maps,
                start=start_time,
                end=None,
                increment=time_step,
                dbif=None,
                interval=False,
            )

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

        mapset = grass.gisenv()["MAPSET"]
        if mode2:
            start_time += 0.5 * time_step
        absolute_time = (datetime.datetime(year, 1, 1) +
                         datetime.timedelta(days=day - 1) +
                         datetime.timedelta(hours=start_time))
        start = absolute_time.strftime("%Y-%m-%d %H:%M:%S")
        step = datetime.timedelta(hours=time_step)
        step = "%d seconds" % step.seconds

        if beam_rad_basename_user:
            registerToTemporal(
                beam_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Beam irradiance" if mode1 else "Beam irradiation",
                desc="Output beam irradiance raster maps [W.m-2]"
                if mode1 else "Output beam irradiation raster maps [Wh.m-2]",
            )
        if diff_rad_basename_user:
            registerToTemporal(
                diff_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Diffuse irradiance" if mode1 else "Diffuse irradiation",
                desc="Output diffuse irradiance raster maps [W.m-2]" if mode1
                else "Output diffuse irradiation raster maps [Wh.m-2]",
            )
        if refl_rad_basename_user:
            registerToTemporal(
                refl_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Reflected irradiance"
                if mode1 else "Reflected irradiation",
                desc="Output reflected irradiance raster maps [W.m-2]" if mode1
                else "Output reflected irradiation raster maps [Wh.m-2]",
            )
        if glob_rad_basename_user:
            registerToTemporal(
                glob_rad_basename_user,
                suffixes_all,
                mapset,
                start,
                step,
                title="Total irradiance" if mode1 else "Total irradiation",
                desc="Output total irradiance raster maps [W.m-2]"
                if mode1 else "Output total irradiation raster maps [Wh.m-2]",
            )
        if incidout_basename:
            registerToTemporal(
                incidout_basename,
                suffixes_all,
                mapset,
                start,
                step,
                title="Incidence angle",
                desc="Output incidence angle raster maps",
            )

    else:
        absolute_time = datetime.datetime(year, 1,
                                          1) + datetime.timedelta(days=day - 1)
        for i, time in enumerate(times):
            grass_time = format_grass_time(absolute_time +
                                           datetime.timedelta(hours=time))
            if beam_rad_basename_user:
                set_time_stamp(beam_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if diff_rad_basename_user:
                set_time_stamp(diff_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if refl_rad_basename_user:
                set_time_stamp(refl_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if glob_rad_basename_user:
                set_time_stamp(glob_rad_basename_user + suffixes_all[i],
                               time=grass_time)
            if incidout_basename:
                set_time_stamp(incidout_basename + suffixes_all[i],
                               time=grass_time)

    if beam_rad_basename_user:
        maps = [beam_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if diff_rad_basename_user:
        maps = [diff_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if refl_rad_basename_user:
        maps = [refl_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if glob_rad_basename_user:
        maps = [glob_rad_basename_user + suf for suf in suffixes_all]
        set_color_table(maps, binary)
    if incidout_basename:
        maps = [incidout_basename + suf for suf in suffixes_all]
        set_color_table(maps)