コード例 #1
0
def domains_folder(folder_input, output, domain):
    if not output:
        output = folder_input
        output = join(folder_input, 'auto_pddls.tmp')
        output = fh.mkdir_from_file(output)
        fdic = join(output, 'dictionary.dat')
        fpddl = join(output, 'auto_domain.pddl')
        ftmpt = join(output, 'template.pddl')

    # pddl.ini
    config = fh.PDDLInit()
    dinit = config.dic_initial_states()

    dprec = {}
    srep = StateRepresentation(folder_input)
    logger.info('Dictionary contaning {} relations.'.format(len(srep)))
    relfiles = fh.FolderHandler(folder_input)
    for file_input in relfiles:
        fname, _ = fh.filename(file_input)
        file_output = join(output, fname + '.pddl')
        # get all preconditions and effects before applying XNORp
        preconditions_effects(file_input, srep, dprec, dinit)

    XNORp(dprec, srep)
    generate_pddl(srep, dprec, fpddl, domain)
    srep.save(fdic)
    generate_template_file(srep, ftmpt, dinit, domain=domain)
コード例 #2
0
def domains_folder(folder_input, output, domain):
    if not output:
        output = folder_input
        output = join(folder_input, 'pddls_full.tmp')
        output = fh.mkdir_from_file(output)
        fdic = join(output, 'dictionary.dat')
        fpddl = join(output, 'domain.pddl')
        ftmpt = join(output, 'template.pddl')

    dprec = {}
    srep = StateRepresentation(folder_input)
    logger.info('Dictionary contaning {} relations.'.format(len(srep)))
    relfiles = fh.FolderHandler(folder_input)
    for file_input in relfiles:
        fname, _ = fh.filename(file_input)
        file_output = join(output, fname + '.pddl')
        # get all preconditions and effects before applying XNORp
        preconditions_effects_pair(file_input, srep, dprec)
    #print(len(dprec))

    #for eff in sorted(dprec):
    #    print(eff, len(dprec[eff]))
    #    print(dprec[id][0])
    #    print(dprec[id][1])
    #    print()

    #XNORp(dprec, srep, convert_null=True)
    convert_to_negative(dprec, srep)

    generate_pddl_pair(srep, dprec, fpddl, domain)
    srep.save(fdic)
    generate_template_file(srep, ftmpt, domain=domain)
コード例 #3
0
def plot_result(csv_file, name=''):
    """ Return the accuracy of scores according to the true class `name`. 

    Parameters:
    -----------
    csv_file: string
        csv file containing scores from the goal recognizer
    """
    fname = fh.filename(csv_file, extension=False)
    fplot = join(dirname(csv_file), fname + '.png')
    df_full = pd.read_csv(csv_file)
    # remove idfr column
    names = list(df_full.columns)[1:]
    df = df_full[names]

    dnames = dict([(i, n) for i, n in enumerate(names)])
    dic = dict([(i, []) for i, n in enumerate(names)])
    for i, scores in enumerate(
            zip(df[names[0]], df[names[1]], df[names[2]], df[names[3]],
                df[names[4]])):
        winner = np.argwhere(scores == np.amax(scores)).flatten().tolist()
        for idname in dnames:
            if idname in winner:
                dic[idname].append(idname)
            else:
                dic[idname].append(-1)

    plt.figure(figsize=(15, 10))
    size = len(dic[0])
    for key in dic:
        plt.scatter(range(size), dic[key])
    plt.ylim(-0.5, 4.5)
    plt.yticks(range(len(names)), names)
    plt.legend(names)
    plt.savefig(fplot)
コード例 #4
0
def compute_from_folder(folder_input, output, plot=False):
    """ Receives a folder containing files with scores for each
        goal.

    Parameters:
    -----------
    folder_input: string
        path to the folder containing files with relations
    output: string
        path to the file where the goals are saved.
    """
    if not output:
        output = join(folder_input, 'results.txt')

    drecipes = {}
    filescores = fh.FolderHandler(folder_input, ext='csv')
    with open(output, 'w') as fout:
        for file_score in filescores:
            logger.info('Reading file: {}'.format(file_score))
            fname = fh.filename(file_score, extension=False).split('-')[1]
            # fname = boiledegg
            acc, correct, spread, nb_obs = compute_accuracy(file_score,
                                                            name=fname)
            fout.write(
                '{}: \n\tAccuracy: {}\n\tCorrect: {}\n\tSpread: {}\n\tObservations: {}\n\n'
                .format(fname, acc, correct, spread, nb_obs))
            if plot:
                plot_result(file_score, name=fname)

    logger.info('Accuracy scores saved in file: {}'.format(output))
コード例 #5
0
def generate_goal_states(folder_input, output):
    """ Generate a file containing the goal states for a set of files
        containing relations between objects. Each recipe has its own
        set of goals. Recipes are grouped according to the name of the
        file, where the defaults uses `<nb_file>-<repipe>.txt` format.

    Parameters:
    -----------
    folder_input: string
        path to the folder containing files with relations
    output: string
        path to the file where the goals are saved.
    """
    if not output:
        output = join(folder_input, 'goal_states.dat')

    drecipes = {}
    relfiles = fh.FolderHandler(folder_input)
    for file_input in relfiles:
        logger.info('Reading file: {}'.format(file_input))
        fname = fh.filename(file_input, extension=False)[2:]
        relations = goal_state_from_file(file_input)
        add_relations(drecipes, fname, relations)

    logger.info('Saving goal states in: {}'.format(output))
    save_goal(drecipes, output)
コード例 #6
0
ファイル: extract_bag.py プロジェクト: rogergranada/_utilsdev
def main_extract(bagname):
    bagname = fh.is_file(bagname)
    fname, ext = fh.filename(bagname)
    if ext == '.bag':
        dirout = fh.mkdir_from_file(bagname)
        logger.info('Reading bag %s' % bagname)
        bag = rosbag.Bag(bagname)
        boat1 = Boat('Boat 1')
        boat2 = Boat('Boat 2')
        sim = Stats(fname)

        dtopics = bag.get_type_and_topic_info()[1]
        bag_messages = bag.read_messages()
        for topic, msg, timestamp in bag_messages:
            if topic == 'diffboat1/state':
                boat1.add_x(msg.pose.pose.position.x)
                boat1.add_y(msg.pose.pose.position.y)
            elif topic == '/diffboat2/state':
                boat2.add_x(msg.pose.pose.position.x)
                boat2.add_y(msg.pose.pose.position.y)
            elif topic == '/diffboat1/move_base/RRAPlannerROS/d_cpa':
                sim.add('dcpa', msg.data)
            elif topic == '/diffboat1/move_base/RRAPlannerROS/t_cpa':
                sim.add('tcpa', msg.data)
            elif topic == '/diffboat1/move_base/RRAPlannerROS/distance':
                sim.add('distance', msg.data)
            elif topic == '/diffboat1/move_base/RRAPlannerROS/computation_time':
                sim.add('computation', msg.data)

        fout = join(dirout, fname + '.pkl')
        logger.info('Saving file: {}'.format(fout))
        d = {'boat1': boat1, 'boat2': boat2, 'stats': sim}
        with open(fout, 'wb') as f:
            pickle.dump(d, f)
コード例 #7
0
def main(inputfile, topics, dirout=None):
    """
    Exclude rows from topic file that do not exist in the final list of images.
    Rename files fixing their names (restart the counter from 0).       
    """
    if not dirout:
        dirout = dirname(inputfile)

    pfi = fh.PathfileHandler(inputfile)
    dnames = {}
    for _ in pfi:
        dnames[fh.filename(pfi.path, string=True)] = ''

    count = 0
    features = ''
    with open(join(dirout, 'rename.txt'), 'w') as ftxt, \
         open(join(dirout, 'topics.csv'), 'w') as ftpc:
        pft = fh.PathfileHandler(topics, sep=';', display=False)
        ftpc.write('%s\n' % pft.header())
        for arr in pft:
            if isinstance(arr, str):
                path = arr
            else:
                path = arr[0]
            if dnames.has_key(path):
                new_path = '%d.jpg' % count
                ftxt.write('%s %s\n' % (path, new_path))
                if len(arr) == 2 and arr[1]:
                    features = ';'.join(arr[1])
                ftpc.write('%s;%s\n' % (new_path, features))
                count += 1
コード例 #8
0
ファイル: plot_data.py プロジェクト: rogergranada/_utilsdev
def main_plot(bagname):
    bagname = fh.is_file(bagname)
    fname, ext = fh.filename(bagname)
    if ext == '.bag':
        dirout = fh.mkdir_from_file(bagname)
        fileinput = join(dirout, fname + '.pkl')
    elif ext == '.pkl':
        dirout = dirname(bagname)
        fileinput = bagname
    else:
        logger.error('File {} is not pickle or bag'.format(bagname))
        sys.exit()
    fileinput = fh.is_file(fileinput)
    logger.info('Reading file: %s' % fileinput)
    with open(fileinput, 'rb') as f:
        dic = pickle.load(f)

    fplot = join(dirout, fname + '_trajectory.pdf')
    logger.info('Saving plot: {}'.format(fplot))
    plot_trajectories(dic['boat1'], dic['boat2'], fplot, angle1=120, angle2=30)

    fplot = join(dirout, fname + '_dcpa.pdf')
    logger.info('Saving plot: {}'.format(fplot))
    plot_distribution(dic['stats'].dic['dcpa'],
                      'Valor de DCPA',
                      fplot,
                      color='tab:blue')

    fplot = join(dirout, fname + '_tcpa.pdf')
    logger.info('Saving plot: {}'.format(fplot))
    plot_distribution(dic['stats'].dic['tcpa'],
                      'Valor de TCPA',
                      fplot,
                      color='tab:orange')

    fplot = join(dirout, fname + '_distance.pdf')
    logger.info('Saving plot: {}'.format(fplot))
    plot_distribution(dic['stats'].dic['distance'],
                      'Distancia em metros',
                      fplot,
                      color='tab:green',
                      mode=True)

    fplot = join(dirout, fname + '_computation.pdf')
    logger.info('Saving plot: {}'.format(fplot))
    plot_distribution(dic['stats'].dic['computation'],
                      'Custo computacional',
                      fplot,
                      color='tab:red')
コード例 #9
0
def main(reference, target, move=False, output=None):
    """ Remove images from `target` that do not exist in `reference` """
    if move and not output:
        output = join(dirname(target), 'removed')
        if not isdir(output):
            legger.info('Creating folder: {}'.format(output))
            os.makedir(output)

    if isdir(reference):
        fout = join(dirname(reference), 'paths_ref.txt')
        fh.create_paths(reference, fout)
        reference = fout
    if isdir(target):
        fout = join(dirname(target), '..', 'paths_target.txt')
        fh.create_paths(target, fout)
        target = fout

    pf = fh.PathfileHandler(reference, display=False)
    dtrue = {}
    for _ in pf:
        name, ext = fh.filename(pf.path)
        fname = '{}{}'.format(name, ext)
        dtrue[fname] = ''

    pf = fh.PathfileHandler(target, display=False)
    for _ in pf:
        name, ext = fh.filename(pf.path)
        fname = '{}{}'.format(name, ext)
        if not dtrue.has_key(fname):
            if move:
                new_path = join(output, fname)
                logger.info('Moving file: %s -> %s' % (pf.path, new_path))
                shutil.move(pf.path, new_path)
            else:
                logger.info('Removing file: %s' % pf.path)
                os.remove(pf.path)