experiment = SimpleFunctionDag(**vars(args))

    assert experiment.confopts["experiment"] in [
        "embedded", "hopbyhop", "remotestate"
    ]
    assert experiment.confopts["bw"] > 0
    assert experiment.confopts["nodes"] >= 1
    assert experiment.confopts["states"] > 0
    assert experiment.confopts["length"] >= 1
    assert experiment.confopts["length"] % 2 == 1
    assert experiment.confopts["branches"] >= 1
    assert experiment.confopts["inputsize"] > 0
    assert experiment.confopts["lambdaspc"] > 0
    assert experiment.confopts["lambdaspc"] * (experiment.confopts["nodes"] - 1) \
        > ((experiment.confopts["length"] + 1) / 2)

    experiment.runExperiment(
        topo.NestedCircularTopo(
            experiment.confopts["nodes"],
            0,
            dict(
                delay="1ms",
                bw=experiment.confopts["bw"],
                loss=0,
                max_queue_size=1000,
                use_htb=True,
            ),
            dict(),
        ))
Exemple #2
0
def main():
    top = tk.Tk()

    # gameState = GameState("../data/maps/map_2.png") #TODO pass in an actual map PNG
    # print(gameState.mapGraph.map_graph)
    # startPoint = list(gameState.mapGraph.get_map())[0]
    # test_agent = agent.bfsAgent(gameState)
    # directions = test_agent.generatePath()
    # for d in directions:
    #     print(d)
    #
    # print("Expaned " + str(test_agent.getCompletionDetails()) + " nodes")
    #mapView = MapView(top, gameState)
    # #print(util.vectorListToSingleSteps(directions))
    # #demoInstrutions = [ActionEnum.EAST, ActionEnum.EAST, ActionEnum.WEST, ActionEnum.NORTH, ActionEnum.WEST, ActionEnum.SOUTH, ActionEnum.WAIT]
    # game = Game(gameState, util.vectorListToSingleSteps(directions), mapView)
    #
    #
    #
    #
    #
    # game.gameLoop()

    results = experiment.runExperiment("../data/maps/map_1.png",
                                       top, {},
                                       showGUI=True)
    results = experiment.runExperiment("../data/maps/map_2.png",
                                       top,
                                       results,
                                       showGUI=True)
    results = experiment.runExperiment("../data/maps/map_3.png",
                                       top,
                                       results,
                                       showGUI=True)

    dict_results = {
        "score": {
            "astar": [],
            "dfs": [],
            "bfs": [],
            "dls": []
        },
        "nodes": {
            "astar": [],
            "dfs": [],
            "bfs": [],
            "dls": []
        }
    }

    #print results
    for type in results.keys():
        print("Type: " + type)
        averageExpanded = 0
        averageScore = 0
        total = 0

        for result in results[type]:
            averageScore += result.score
            averageExpanded += result.nodesExpanded
            total += 1
            print(result)

            dict_results["score"][type].append(result.score)
            dict_results["nodes"][type].append(result.nodesExpanded)

        averageExpanded = averageExpanded / total
        averageScore = averageScore / total

        print("Average Score: " + str(averageScore) + " Average Expanded: " +
              str(averageExpanded))

        with open('data.json', 'w', newline='\n') as jsonfile:
            jsonfile.write(json.dumps(dict_results))
            [str, 'grpc', 'experiment type, one of: grpc, quic, quic0rtt'],
            'bw': [
                float, 100,
                'link bandwidth, one of: 0.01, 0.1, 1, 10, 100, 1000'
            ],
            'delay': [str, '100us', 'link delays, one of: 1us, 100us, 10ms'],
            'size':
            [int, 1000, 'lambda request input size, one of: 100, 1000, 10000']
        }, {
            'cpu_limit': -1.0,
            'nat': False,
            'controller': 'flat',
            'balancing': 'rr-async',
            'edgetype': 'router',
            'tclink': 'wotc'
        })

    experiment = LinearQuic(**vars(args))

    experiment.runExperiment(
        topo.LinearTopo(
            4,  # hosts
            # linkargs
            dict(
                bw=experiment.confopts['bw'],  # <<<<<<<<<<<<<<<<
                delay=experiment.confopts['delay'],  # <<<<<<<<<<<
                loss=0,
                max_queue_size=1000,
                use_htb=True),
            dict()))  # hostargs
Exemple #4
0
                'distributed',
                'experiment type, one of: distributed, centralized'
            ],
            'lambda_protocol': [
                str,
                'grpc',
                'one of: grpc, quic, quic-0rtt'
            ]
        },
        {
            'cpu_limit': -1.0,
            'balancing': 'rr-async',
            'nat': False,
            'edgetype': 'router',
            'tclink': 'wotc',
            'pingtest': 'none'
        })

    experiment = QuicComputerChicago(**vars(args))

    experiment.runExperiment(
        topo.BriteTopo(
            args.verbosity >= 1,
            'nodes.topo',
            dict(
                bw=10,
                delay='10ms',
                loss=0,
                max_queue_size=1000,
                use_htb=True)))
instructionsText = ''
if validationRun:
	instructionsText = 'In this experiment you will see a series of images that repeat multiple times. There will be a white fixation cross (+) located in the center of the screen. We ask that you maintain focus on the cross at all times. \n\n Your task is to judge whether they are negative, neutral or positive. For negative press the leftmost button with your index finger, for neutral the second button with your middle finger, and for positive the third button with your ring finger. Categorize each image as quickly as you can. Since you will see multiple presentations of eaceh image, it is ok if you change your rating for successive viewings.\n\nPlease let your experimenter know when you are ready to continue...'
else:
 	instructionsText = 'In this experiment you will see a series of images. There will be a white fixation cross (+) located in the center of the screen. We ask that you maintain focus on the cross at all times. \n\n Your task is to judge whether they are negative, neutral or positive. For negative press the leftmost button with your index finger, for neutral the second button with your middle finger, and for positive the third button with your ring finger. Categorize each image as quickly as you can.\n\nPlease let your experimenter know when you are ready to continue...'

# use this function to initialize vision egg, open the log file,
# read in the input files and display the instructions
experiment.quickInit(logFilename, stimFilename, imagesFilename, visualAngleFilename, instructionsText)

########################################
# Add all Experiment handlers          #
########################################

# add a time handler which will turn the stimulus off after 1 second
experiment.addTimeHandler(StimOffTimeHandler(experiment,offTime=1))

# add a handler that will record the inputs from the scanner's 4 Button response box
experiment.addKeyHandler(Scanner4ButtonKeyHandler(experiment))

# tell the experiment that a trial ends after 4 seconds
experiment.setTrialFinishedHandler(TimeTrialFinishedHandler(experiment,seconds=4.0))

########################################
# Start the Experiment Loop            #
########################################

# finally, start the experiment loop which will display
# all the stimuli using the handlers crated above
experiment.runExperiment()
            [int, 1000, 'lambda request input size, one of: 100, 1000, 10000'],
            'loss': [int, 0, 'link loss probability'],
            'numclients': [int, 1, 'number of client threads']
        }, {
            'cpu_limit': -1.0,
            'nat': False,
            'controller': 'flat',
            'balancing': 'rr-async',
            'edgetype': 'router',
            'tclink': 'wotc',
            'pingtest': 'none'
        })

    experiment = QuicRouterComputer(**vars(args))

    # delay and bandwidth
    link_types = {
        'slow': ['50ms', 1],
        'medium': ['10ms', 10],
        'fast': ['100us', 100],
    }

    experiment.runExperiment(
        topo.LinearTopo(
            4,
            dict(delay=link_types[experiment.confopts['link']][0],
                 bw=link_types[experiment.confopts['link']][1],
                 loss=experiment.confopts['loss'],
                 max_queue_size=1000,
                 use_htb=True), dict()))

if __name__ == "__main__":
    args = experiment.Experiment.makeArgumentParser(
        {
            "experiment": [
                str,
                "client",
                "experiment type, one of: client, edge, cloud",
            ],
            "statesize": [int, 1000, "state size, in kB"],
            "inputsize": [int, 1000, "input size, in kB"],
        },
        {
            "cpu_limit": -1.0,
            "nat": False,
            "controller": "flat",
            "balancing": "rr-async",
            "edgetype": "router",
            "tclink": "wotc",
            "pingtest": "none",
        },
    )

    experiment = MotivationDag(**vars(args))

    assert experiment.confopts["experiment"] in ["client", "edge", "cloud"]
    assert experiment.confopts["statesize"] > 0

    experiment.runExperiment(MotivationTopo())
def main():
    """Driver. Typically run from __main__ in the program that uses the driver."""
    parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("config", help="Main Config File")
    parser.add_argument(
        "--experiment",
        help=
        "Run an experiment according to the [experiment] section, with the results in this directory",
        action='store_true')
    parser.add_argument("--isolation",
                        help="Specifies isolation mode for experiments",
                        choices=['sameprocess', 'subprocess'],
                        default='sameprocess')
    parser.add_argument(
        "--graphdata",
        help="Just draw the graph from the data that was already collected.",
        action='store_true')

    ctools.clogging.add_argument(parser)
    args = parser.parse_args()

    if not os.path.exists(args.config):
        raise RuntimeError("{} does not exist".format(args.config))

    if args.graphdata and args.experiment is None:
        parser.error("--graphdata requires --experiment")

    ###
    ### Read the configuration file
    ###

    config = HierarchicalConfigParser()
    config.read(args.config)

    ###
    ### Logging must be set up before any logging is done
    ### By default is is in the current directory, but if we run an experiment, put the logfile in that directory
    ### Added option to put logs in a subfolder specified in the config
    isodate = datetime.datetime.now().isoformat()[0:19]
    if config.has_section(LOGGING_SECTION) and config.has_option(
            LOGGING_SECTION, LOGFOLDER_OPTION) and config.has_option(
                LOGGING_SECTION, LOGFILENAME_OPTION):
        logfname = f"{config[LOGGING_SECTION][LOGFOLDER_OPTION]}/{config[LOGGING_SECTION][LOGFILENAME_OPTION]}-{isodate}-{os.getpid()}.log"
    else:
        logfname = f"{isodate}-{os.getpid()}.log"
    dfxml = DFXMLWriter(filename=logfname.replace(".log", ".dfxml"),
                        prettyprint=True)

    # Left here for backward compatibility, to be removed in future versions
    if args.experiment:
        if not os.path.exists(args.experiment):
            os.makedirs(args.experiment)
        if not os.path.isdir(args.experiment):
            raise RuntimeError("{} is not a directory".format(args.experiment))
        config['DEFAULT'][ROOT] = args.experiment
        logfname = os.path.join(args.experiment, logfname)
    ####

    # Make sure the directory for the logfile exists. If not, make it.
    logdirname = os.path.dirname(logfname)
    if logdirname and not os.path.exists(logdirname):
        print("driver.py: os.mkdir({})".format(logdirname))
        os.mkdir(logdirname)

    ctools.clogging.setup(args.loglevel, syslog=True, filename=logfname)
    logging.info("START {}  log level: {}".format(os.path.abspath(__file__),
                                                  args.loglevel))

    t0 = time.time()

    log_testpoint("T03-002S")

    #########################
    # Set up the experiment #
    #########################

    # if there is no experiment section in the config file, add one
    if EXPERIMENT not in config:
        config.add_section(EXPERIMENT)

    # If there is no run experiment flag in the config section, add it
    run_experiment = config[EXPERIMENT].getint(RUN_EXPERIMENT_FLAG, 0)

    # If --experiment was specified, set run_experiment to run
    if args.experiment:
        run_experiment = 1

    ### Now validate and apply the config file
    config_validate(config)
    config_apply_environment(config)

    #############################
    # Create the DAS
    #############################
    das = DAS(config)

    #############################
    # DAS Running Section.
    # Option 1 - run_experiment
    # Option 2 - just run the das
    #############################
    logging.debug("Just before Experiment")

    if run_experiment:
        # set up the Experiment module
        try:
            (experiment_file,
             experiment_class_name) = config[EXPERIMENT][EXPERIMENT].rsplit(
                 ".", 1)
        except KeyError:
            (experiment_file,
             experiment_class_name) = ('driver', 'AbstractDASExperiment')
        try:
            experiment_module = __import__(experiment_file,
                                           fromlist=[experiment_class_name])
        except ImportError as e:
            print("Module import failed.")
            print("current directory: {}".format(os.getcwd()))
            print("__file__: {}".format(__file__))
            raise e

        experiment = getattr(experiment_module,
                             experiment_class_name)(das=das,
                                                    config=das.config,
                                                    name=EXPERIMENT)
        logging.debug("Running DAS Experiment. Logfile: {}".format(logfname))

        experiment_data = experiment.runExperiment()

    else:
        #### Run the DAS without an experiment
        logging.debug(
            "Running DAS without an experiment. Logfile: {}".format(logfname))
        try:
            data = das.run()
        except Exception as e:
            log_testpoint("T03-005F")
            raise (e)

    ###
    ### Shutdown
    ###
    t1 = time.time()
    t = t1 - t0
    logging.info("Elapsed time: {:.2} seconds".format(t))
    logging.info("END {}".format(os.path.abspath(__file__)))
    logging.shutdown()
    print("*****************************************************")
    print("driver.py: Run completed in {:,.2f} seconds. Logfile: {}".format(
        t, logfname))