예제 #1
0
    def setup_spinnman_interfaces(self):
        """Set up the interfaces for communicating with the SpiNNaker board
        """
        self.dao.set_hostname(self.hostname)
        self.txrx = Transceiver(self.hostname)

        # Start local tubotron if requested
        if conf.config.getboolean("Visualiser", "enable"):
            self.wait_for_run = conf.config.getboolean(
                "Visualiser", "pause_before_run"
            )
            if self.wait_for_run:
                self.visualiser = Visualiser(
                    self.dao, start_simulation_method=getattr(self, "run_now")
                )
            else:
                self.visualiser = Visualiser(self.dao)
            self.visualiser.set_port(self.visualiser_port)

        tubotron_port = conf.config.getint("Tubotron", "port")
        tubotron_tag = conf.config.getint("Tubotron", "tag")
        tubotron_host = conf.config.get("Tubotron", "hostname")

        self.set_tag_output(tubotron_tag, tubotron_port, tubotron_host)

        if conf.config.getboolean("Tubotron", "enable"):
            if tubotron_host == "localhost":
                self.tubotron = Tubotron(tubotron_port)
            if conf.config.has_option("Tubotron", "leaveRunning"):
                self.leaveTubotronRunning = conf.config.getboolean(
                    "Tubotron", "leaveRunning")
예제 #2
0
    def setup_spinnman_interfaces(self):
        """Set up the interfaces for communicating with the SpiNNaker board
        """
        self.dao.set_hostname(self.hostname)
        self.txrx = Transceiver(self.hostname)

        # Start local tubotron if requested
        if conf.config.getboolean("Visualiser", "enable"):
            self.wait_for_run = conf.config.getboolean("Visualiser",
                                                       "pause_before_run")
            if self.wait_for_run:
                self.visualiser = Visualiser(self.dao,
                                             start_simulation_method=getattr(
                                                 self, "run_now"))
            else:
                self.visualiser = Visualiser(self.dao)
            self.visualiser.set_port(self.visualiser_port)

        tubotron_port = conf.config.getint("Tubotron", "port")
        tubotron_tag = conf.config.getint("Tubotron", "tag")
        tubotron_host = conf.config.get("Tubotron", "hostname")

        self.set_tag_output(tubotron_tag, tubotron_port, tubotron_host)

        if conf.config.getboolean("Tubotron", "enable"):
            if tubotron_host == "localhost":
                self.tubotron = Tubotron(tubotron_port)
            if conf.config.has_option("Tubotron", "leaveRunning"):
                self.leaveTubotronRunning = conf.config.getboolean(
                    "Tubotron", "leaveRunning")
예제 #3
0
def trigger_page():
    """
    Renders the trigger page. This page contains an instance of a TriggerForm.
    The TriggerForm contains input fields for the simulation. If the submit
    button is pressed, a simulation is triggered and the results are generated
    using the Visualiser class. If all succeeds, forward to endpoint "visualise"
    """
    form = TriggerForm()

    # if the form is valid and the submit button was pressed
    if form.validate_on_submit():

        # get the static path from the current application to store the visualisations
        static_path = os.path.join(current_app.root_path,
                                   current_app.static_folder)

        # clean up the previous simulation results
        Cleaner().remove_previous_simulation_results(static_path=static_path)

        # retrieve number of requests from the form
        number_of_requests = form.number_of_requests_field.data

        # Create an instance of the bounding box class, using the form data
        bounding_box = BoundingBox((form.x1_field.data, form.y1_field.data,
                                    form.x2_field.data, form.y2_field.data))

        # Create an instance of the StaticDataReader class.
        static_data = StaticDataReader(
            berlin_bounds_file=current_app.config['BERLIN_BOUNDS_FILE'],
            berlin_stops_file=current_app.config['BERLIN_STOPS_FILE'])

        # Create an instance of the Simulator class.
        simulator = Simulator(
            bounding_box=bounding_box.bounding_box,
            path_to_stops=current_app.config['BERLIN_STOPS_FILE'])
        # Run a simulation
        simulation_results = simulator.simulate(number_of_requests)

        # Create an instance of the Visualiser class.
        visualiser = Visualiser(bounding_box=bounding_box,
                                simulation_results=simulation_results,
                                static_path=static_path,
                                static_data=static_data)

        # Generate visualisations
        visualiser.generate_overview_figure()
        visualiser.generate_closeup_figure()
        visualiser.generate_gmap()

        # redirect to the visualise endpoint
        return redirect(
            url_for('routes.visualise', visualiser_id=visualiser.id))

    # render a template for the trigger page.
    return render_template('trigger_page.html',
                           title="MI Code Challenge",
                           form=form)
    def setUpClass(self):
        """
        Sets up the class. The data only has to be read in once, so this is done in the class setup method.
        """
        # TODO: Remove warn ngs filter when migrating to geopandas > 0.7.0 !
        warnings.simplefilter('ignore', category=FutureWarning)
        warnings.simplefilter('ignore', category=DeprecationWarning)

        static_data = StaticDataReader('data/berlin_bounds.poly',
                                       'data/berlin_stops.geojson')
        bounding_box_tuple = (13.34014892578125, 52.52791908000258,
                              13.506317138671875, 52.562995039558004)
        simulator = Simulator(bounding_box=bounding_box_tuple)
        simulation_results = simulator.simulate(number_of_requests=6)

        self.visualiser = Visualiser(
            bounding_box=BoundingBox(bounding_box_tuple),
            simulation_results=simulation_results,
            static_data=static_data,
            static_path='webapp/static')
        [2, 3, 2, 3]
        [2, 3, 3, 2]
        [3, 2, 2, 3]
        [3, 2, 3, 2]
        [3, 3, 2, 2]
        [3, 7]
        [7, 3]
"""


@vs(ignore_args=['node_num'], show_argument_name=False, show_return_value=False)
def f(sum, ans):
    # If sum becoms 0 we have found the required list
    if sum == 0:
        print(ans)

    # Include every other element to make the sum
    # Number that is included also can be included
    for elem in nums:
        if sum - elem >= 0:
            f(sum=sum - elem, ans=ans + [elem])


# We want to make the sum from list nums
nums = [2, 3, 7]
sum = 10

# Call solve with sum and an empty list
f(sum=sum, ans=[])
vs.write_image("make_sum.png")
예제 #6
0
class Controller(object):
    """
    A Controller is instantiated by a front-end in order to map a model to
    SpiNNaker, load it to the machine, run it and retrieve the results.
    The Controller provides functions for the front-end to trigger each of
    these stages and instantiates a :py:class:`pacman103.core.dao.DAO` object
    in which front-end inputs and results of the mapping processes are stored
    and a :py:class:`pacman103.core.transceiver.Transceiver` through which
    simulations are loaded to SpiNNaker and observed.

    :param module front_end:
        front-end package
    :param string hostname:
        hostname of the SpiNNaker machine on which the simulation is to be run.
    :param dict kwargs:
        key word arguments, of which there are currently none.
    """

    partitioner_algorithms_list = conf.get_valid_components(
        partitioner_algorithms, "Partitioner"
    )

    placer_algorithms_list = conf.get_valid_components(
        placer_algorithms, "Placer"
    )

    key_allocator_algorithms_list = conf.get_valid_components(
        key_allocator_algorithms, "KeyAllocator"
    )

    routing_algorithms_list = conf.get_valid_components(
        routing_algorithms, "Routing"
    )

    utility = None

    def __init__(self, front_end, hostname, reload_time=None, **kwargs):
        self.hostname = hostname
        self.dao = dao.DAO(front_end)
        self.reload_time = reload_time

        self.txrx = None
        self.app_id = None
        self.tubotron = None
        self.leaveTubotronRunning = False
        self.visualiser = None
        self.wait_for_run = False
        self.visualiser_port = None

        #setting tuborotron to false, so that in theory our strange tubotron doesnt operate
        conf.config.set("Tubotron", "enable", "False")


    #ABS changed so that iptag is sotred into dao instead of
    # transmitting immediately
    def set_tag_output(self, tag, port, hostname="localhost", timeout=10):
        self.dao.add_iptag(IPTag(tag=tag, port=port,
                                 hostname=hostname, timeout=timeout))

    def add_vertex(self, vertex):
        """
        Adds a vertex object to the datastore. This is simply a convenience
        function that wraps :py:func:`pacman103.core.dao.DAO.add_vertex` to
        save the front-end from directly interacting with the datastore.

        :param `pacman103.lib.graph.Vertex` vertex:
            Vertex object to be added.
        """
        return self.dao.add_vertex(vertex)

    def get_multi_cast_vertex(self):
        return self.dao.multi_cast_vertex

    def add_edge(self, edge):
        """
        Adds an edge object to the datastore. This is simply a convenience
        function that wraps :py:func:`pacman103.core.dao.DAO.add_edge` to save
        the front-end from directly interacting with the datastore.

        :param `pacman103.lib.graph.Edge` edge:
            Edge object to be added.
        """
        self.dao.add_edge(edge)

    def add_rng(self, rngIndex, rngInfo):
        """Adds a random number generator object to the datastore. This is
        simply a convenience function that wraps
        :py:func:`pacman103.core.dao.DAO.add_rng` to save the front-end from
        directly interacting with the datastore.
        """
        logger.debug("Controller adding RNG")
        self.dao.add_rng(rngIndex, rngInfo)

    def add_random_distribution(self, distIndex, distInfo):
        """
        Adds a random distribution object to the datastore. This is simply a
        convenience function that wraps
        :py:func:`pacman103.core.dao.DAO.add_randomDistribution` to save the
        front-end from directly interacting with the datastore.
        """
        logger.debug("Controller adding random dist")
        self.dao.add_randomDistribution(distIndex, distInfo)

    def generate_output(self):
        """
        Generates simulation data structures and prepares load targets and
        execution targets.
        """
        if self.reload_time is None:
            output_generator.generate_output(self.dao)
        else:
            output_generator.reload_output(self.dao, self.reload_time)

    def load_write_mem(self):
        """
        Loads the simulation memory writes to the board via the transceiver.
        """
        self.txrx.load_write_mem(self.dao)

    def load_targets(self):
        """
        Loads the simulation executables and data structures to the board via
        the transceiver.
        """
        self.txrx.load_targets(self.dao)

    def map_model(self):
        """Map an input graph to a SpiNNaker machine via the partitioning,
        placement and routing stages. See :py:mod:`pacman103.core.mapper` for
        more details.

        *Side effects*:
            populates the datastore with information proceeding from each stage
            of mapping.
        """
        self.setup_spinnman_interfaces()

        report_dir = self.dao.get_reports_directory()
        enabledReports = False
        if (conf.config.getboolean("Reports", "reportsEnabled")):
            enabledReports = True
        if enabledReports:
            reports.generate_network_report(self.dao)
            reports.generate_machine_report(self.dao)
        #check if each flag has been set before running a method
        #partitioning verts into subverts
        if not self.dao.done_partitioner:
            self.execute_partitioning()

        # placing subverts onto machine structure
        # (can be done by preivous systems if merged)
        if not self.dao.done_placer:
            self.execute_placer()
        if enabledReports:
            reports.generate_placement_reports(self.dao)

        #allocate keys to subedges so that its done up front
        # (no report, as covered by the router report)
        if not self.dao.done_key_allocation:
            self.execute_key_alloc()

        #route packets from subverts through subedges
        if not self.dao.done_router:
            self.filterSubEdges(self.dao)
            self.execute_routing()
        if enabledReports:
            reports.generate_routing_report(self.dao)

        #if not self.dao.done_inverse_mapper:
        #    InverseMapper.build_inverse_map(self.dao)
        if enabledReports:
            reports.generate_coremap_report(self.dao)

    def execute_partitioning(self):
        """Handle the execution of a partitioning algorithm
        """
        try:
            partitioner_class = Controller.partitioner_algorithms_list[
                conf.config.get("Partitioner", "algorithm")]
            partitioner = partitioner_class(self.dao)
            partitioner.partition()
        except KeyError as e:
            raise ValueError("Invalid partitioner algorithm specified. "
                             " I don't know '%s'." % e)

    def execute_placer(self):
        """Handle the exeuction of a placer algorithm
        """
        try:
            placer_class = Controller.placer_algorithms_list[
                conf.config.get("Placer", "algorithm")
            ]
            placer = placer_class(self.dao)
            placer.place_all()
        except KeyError as e:
            raise ValueError("Invalid partitioner algorithm specified. "
                             " I don't know '%s'." % e)

    def execute_key_alloc(self):
        """Handle the execution of a key allocator
        """
        try:
            key_allocator_class = Controller.key_allocator_algorithms_list[
                conf.config.get("Key_allocator", "algorithm")]
            key_allocer = key_allocator_class(self.dao)
            key_allocer.allocate_keys()
        except KeyError as e:
            raise ValueError("Invalid key alloc algorithm specified. "
                             " I don't know '%s'." %
                             conf.config.get("Key_allocator", "algorithm")
                             )

    def execute_routing(self):
        """Execute routing
        """
        try:
            router = Router(self.dao)
            router.route()
        except KeyError as e:
            raise ValueError("Invalid partitioner algorithm specified. "
                             " I don't know '%s'." % e)

    def start_visualiser(self):
        """Start the Visualiser thread
        """
        if (conf.config.getboolean("Visualiser", "enable") and not
                conf.config.getboolean("Visualiser", "have_board")):
                self.visualiser.start()

    def set_visulaiser_port(self, port):
        """Set the port that the Visualiser listens to for packets
        """
        self.visualiser_port = port

    def setup_spinnman_interfaces(self):
        """Set up the interfaces for communicating with the SpiNNaker board
        """
        self.dao.set_hostname(self.hostname)
        self.txrx = Transceiver(self.hostname)

        # Start local tubotron if requested
        if conf.config.getboolean("Visualiser", "enable"):
            self.wait_for_run = conf.config.getboolean(
                "Visualiser", "pause_before_run"
            )
            if self.wait_for_run:
                self.visualiser = Visualiser(
                    self.dao, start_simulation_method=getattr(self, "run_now")
                )
            else:
                self.visualiser = Visualiser(self.dao)
            self.visualiser.set_port(self.visualiser_port)

        tubotron_port = conf.config.getint("Tubotron", "port")
        tubotron_tag = conf.config.getint("Tubotron", "tag")
        tubotron_host = conf.config.get("Tubotron", "hostname")

        self.set_tag_output(tubotron_tag, tubotron_port, tubotron_host)

        if conf.config.getboolean("Tubotron", "enable"):
            if tubotron_host == "localhost":
                self.tubotron = Tubotron(tubotron_port)
            if conf.config.has_option("Tubotron", "leaveRunning"):
                self.leaveTubotronRunning = conf.config.getboolean(
                    "Tubotron", "leaveRunning")

    def run(self, app_id):
        """Trigger execution of the simulation on SpiNNaker via the
        transceiver.
        """
        self.app_id = app_id
        if (conf.config.getboolean("Visualiser", "enable") and
                conf.config.getboolean("Visualiser", "have_board")):
            self.visualiser.start()
        if not self.wait_for_run:
            self.run_now()
        else:
            print "Waiting for run command..."
            self.visualiser.wait_for_finish()

    def run_now(self):
        """Start a already loaded application
        """
        if self.tubotron is not None:
            self.tubotron.start()
            if (self.dao.run_time is not None and self.dao.run_time > 0 
                   and not self.leaveTubotronRunning):
                self.tubotron.set_timeout((self.dao.run_time / 1000.0) + 1)
        self.txrx.run(self.dao, self.app_id)

    def stop(self):
        """Stop a running application
        """
        if self.tubotron is not None:
            self.tubotron.stop()

    def filterSubEdges(self, dao):
        """Go through the newly created list of sub-edges and call a model
        specific function on each one, this allows the application to prune
        sub-edges that are not really needed.
        """
        logger.info("* Running pre-routing sub-edge pruning *")
        new_subedges = list()
        progress = ProgressBar(len(dao.subedges))
        for subedge in dao.subedges:
            if subedge.edge.filterSubEdge(subedge):
                subedge.pruneable = True
            else:
                new_subedges.append(subedge)
            progress.update()
        dao.subedges = new_subedges
        
        progress.end()
예제 #7
0
from visualiser.visualiser import Visualiser as vs

st = []


@vs(show_argument_name=False,
    node_properties_kwargs={
        "shape": "record",
        "color": "#f57542",
        "style": "filled",
        "fillcolor": "grey"
    })
def combi(prefix, s):
    if len(s) == 0:
        return " "
    else:
        st.append(prefix + s[0])
        combi(prefix=prefix + s[0], s=s[1:])
        combi(prefix=prefix, s=s[1:])
        return st


print(combi(prefix="", s='abc'))
vs.make_animation("combinations.gif", delay=3)
예제 #8
0
def main():
    # Call function
    print(fact(n=6))
    # Save recursion tree to a file
    vs.make_animation("factorial.gif", delay=2)
예제 #9
0
def main():
    # Call function
    print(fib(6))
    vs.write_image("tree.png")
def main():
    # Call function
    print(merge_sort([5, 0, 1, 9]))
    # Save recursion tree to a file
    vs.make_animation("merge_sort.gif", delay=1.3)
예제 #11
0
class Controller(object):
    """
    A Controller is instantiated by a front-end in order to map a model to
    SpiNNaker, load it to the machine, run it and retrieve the results.
    The Controller provides functions for the front-end to trigger each of
    these stages and instantiates a :py:class:`pacman103.core.dao.DAO` object
    in which front-end inputs and results of the mapping processes are stored
    and a :py:class:`pacman103.core.transceiver.Transceiver` through which
    simulations are loaded to SpiNNaker and observed.

    :param module front_end:
        front-end package
    :param string hostname:
        hostname of the SpiNNaker machine on which the simulation is to be run.
    :param dict kwargs:
        key word arguments, of which there are currently none.
    """

    partitioner_algorithms_list = conf.get_valid_components(
        partitioner_algorithms, "Partitioner")

    placer_algorithms_list = conf.get_valid_components(placer_algorithms,
                                                       "Placer")

    key_allocator_algorithms_list = conf.get_valid_components(
        key_allocator_algorithms, "KeyAllocator")

    routing_algorithms_list = conf.get_valid_components(
        routing_algorithms, "Routing")

    utility = None

    def __init__(self, front_end, hostname, reload_time=None, **kwargs):
        self.hostname = hostname
        self.dao = dao.DAO(front_end)
        self.reload_time = reload_time

        self.txrx = None
        self.app_id = None
        self.tubotron = None
        self.leaveTubotronRunning = False
        self.visualiser = None
        self.wait_for_run = False
        self.visualiser_port = None

        #setting tuborotron to false, so that in theory our strange tubotron doesnt operate
        conf.config.set("Tubotron", "enable", "False")

    #ABS changed so that iptag is sotred into dao instead of
    # transmitting immediately
    def set_tag_output(self, tag, port, hostname="localhost", timeout=10):
        self.dao.add_iptag(
            IPTag(tag=tag, port=port, hostname=hostname, timeout=timeout))

    def add_vertex(self, vertex):
        """
        Adds a vertex object to the datastore. This is simply a convenience
        function that wraps :py:func:`pacman103.core.dao.DAO.add_vertex` to
        save the front-end from directly interacting with the datastore.

        :param `pacman103.lib.graph.Vertex` vertex:
            Vertex object to be added.
        """
        return self.dao.add_vertex(vertex)

    def get_multi_cast_vertex(self):
        return self.dao.multi_cast_vertex

    def add_edge(self, edge):
        """
        Adds an edge object to the datastore. This is simply a convenience
        function that wraps :py:func:`pacman103.core.dao.DAO.add_edge` to save
        the front-end from directly interacting with the datastore.

        :param `pacman103.lib.graph.Edge` edge:
            Edge object to be added.
        """
        self.dao.add_edge(edge)

    def add_rng(self, rngIndex, rngInfo):
        """Adds a random number generator object to the datastore. This is
        simply a convenience function that wraps
        :py:func:`pacman103.core.dao.DAO.add_rng` to save the front-end from
        directly interacting with the datastore.
        """
        logger.debug("Controller adding RNG")
        self.dao.add_rng(rngIndex, rngInfo)

    def add_random_distribution(self, distIndex, distInfo):
        """
        Adds a random distribution object to the datastore. This is simply a
        convenience function that wraps
        :py:func:`pacman103.core.dao.DAO.add_randomDistribution` to save the
        front-end from directly interacting with the datastore.
        """
        logger.debug("Controller adding random dist")
        self.dao.add_randomDistribution(distIndex, distInfo)

    def generate_output(self):
        """
        Generates simulation data structures and prepares load targets and
        execution targets.
        """
        if self.reload_time is None:
            output_generator.generate_output(self.dao)
        else:
            output_generator.reload_output(self.dao, self.reload_time)

    def load_write_mem(self):
        """
        Loads the simulation memory writes to the board via the transceiver.
        """
        self.txrx.load_write_mem(self.dao)

    def load_targets(self):
        """
        Loads the simulation executables and data structures to the board via
        the transceiver.
        """
        self.txrx.load_targets(self.dao)

    def map_model(self):
        """Map an input graph to a SpiNNaker machine via the partitioning,
        placement and routing stages. See :py:mod:`pacman103.core.mapper` for
        more details.

        *Side effects*:
            populates the datastore with information proceeding from each stage
            of mapping.
        """
        self.setup_spinnman_interfaces()

        report_dir = self.dao.get_reports_directory()
        enabledReports = False
        if (conf.config.getboolean("Reports", "reportsEnabled")):
            enabledReports = True
        if enabledReports:
            reports.generate_network_report(self.dao)
            reports.generate_machine_report(self.dao)
        #check if each flag has been set before running a method
        #partitioning verts into subverts
        if not self.dao.done_partitioner:
            self.execute_partitioning()

        # placing subverts onto machine structure
        # (can be done by preivous systems if merged)
        if not self.dao.done_placer:
            self.execute_placer()
        if enabledReports:
            reports.generate_placement_reports(self.dao)

        #allocate keys to subedges so that its done up front
        # (no report, as covered by the router report)
        if not self.dao.done_key_allocation:
            self.execute_key_alloc()

        #route packets from subverts through subedges
        if not self.dao.done_router:
            self.filterSubEdges(self.dao)
            self.execute_routing()
        if enabledReports:
            reports.generate_routing_report(self.dao)

        #if not self.dao.done_inverse_mapper:
        #    InverseMapper.build_inverse_map(self.dao)
        if enabledReports:
            reports.generate_coremap_report(self.dao)

    def execute_partitioning(self):
        """Handle the execution of a partitioning algorithm
        """
        try:
            partitioner_class = Controller.partitioner_algorithms_list[
                conf.config.get("Partitioner", "algorithm")]
            partitioner = partitioner_class(self.dao)
            partitioner.partition()
        except KeyError as e:
            raise ValueError("Invalid partitioner algorithm specified. "
                             " I don't know '%s'." % e)

    def execute_placer(self):
        """Handle the exeuction of a placer algorithm
        """
        try:
            placer_class = Controller.placer_algorithms_list[conf.config.get(
                "Placer", "algorithm")]
            placer = placer_class(self.dao)
            placer.place_all()
        except KeyError as e:
            raise ValueError("Invalid partitioner algorithm specified. "
                             " I don't know '%s'." % e)

    def execute_key_alloc(self):
        """Handle the execution of a key allocator
        """
        try:
            key_allocator_class = Controller.key_allocator_algorithms_list[
                conf.config.get("Key_allocator", "algorithm")]
            key_allocer = key_allocator_class(self.dao)
            key_allocer.allocate_keys()
        except KeyError as e:
            raise ValueError("Invalid key alloc algorithm specified. "
                             " I don't know '%s'." %
                             conf.config.get("Key_allocator", "algorithm"))

    def execute_routing(self):
        """Execute routing
        """
        try:
            router = Router(self.dao)
            router.route()
        except KeyError as e:
            raise ValueError("Invalid partitioner algorithm specified. "
                             " I don't know '%s'." % e)

    def start_visualiser(self):
        """Start the Visualiser thread
        """
        if (conf.config.getboolean("Visualiser", "enable")
                and not conf.config.getboolean("Visualiser", "have_board")):
            self.visualiser.start()

    def set_visulaiser_port(self, port):
        """Set the port that the Visualiser listens to for packets
        """
        self.visualiser_port = port

    def setup_spinnman_interfaces(self):
        """Set up the interfaces for communicating with the SpiNNaker board
        """
        self.dao.set_hostname(self.hostname)
        self.txrx = Transceiver(self.hostname)

        # Start local tubotron if requested
        if conf.config.getboolean("Visualiser", "enable"):
            self.wait_for_run = conf.config.getboolean("Visualiser",
                                                       "pause_before_run")
            if self.wait_for_run:
                self.visualiser = Visualiser(self.dao,
                                             start_simulation_method=getattr(
                                                 self, "run_now"))
            else:
                self.visualiser = Visualiser(self.dao)
            self.visualiser.set_port(self.visualiser_port)

        tubotron_port = conf.config.getint("Tubotron", "port")
        tubotron_tag = conf.config.getint("Tubotron", "tag")
        tubotron_host = conf.config.get("Tubotron", "hostname")

        self.set_tag_output(tubotron_tag, tubotron_port, tubotron_host)

        if conf.config.getboolean("Tubotron", "enable"):
            if tubotron_host == "localhost":
                self.tubotron = Tubotron(tubotron_port)
            if conf.config.has_option("Tubotron", "leaveRunning"):
                self.leaveTubotronRunning = conf.config.getboolean(
                    "Tubotron", "leaveRunning")

    def run(self, app_id):
        """Trigger execution of the simulation on SpiNNaker via the
        transceiver.
        """
        self.app_id = app_id
        if (conf.config.getboolean("Visualiser", "enable")
                and conf.config.getboolean("Visualiser", "have_board")):
            self.visualiser.start()
        if not self.wait_for_run:
            self.run_now()
        else:
            print "Waiting for run command..."
            self.visualiser.wait_for_finish()

    def run_now(self):
        """Start a already loaded application
        """
        if self.tubotron is not None:
            self.tubotron.start()
            if (self.dao.run_time is not None and self.dao.run_time > 0
                    and not self.leaveTubotronRunning):
                self.tubotron.set_timeout((self.dao.run_time / 1000.0) + 1)
        self.txrx.run(self.dao, self.app_id)

    def stop(self):
        """Stop a running application
        """
        if self.tubotron is not None:
            self.tubotron.stop()

    def filterSubEdges(self, dao):
        """Go through the newly created list of sub-edges and call a model
        specific function on each one, this allows the application to prune
        sub-edges that are not really needed.
        """
        logger.info("* Running pre-routing sub-edge pruning *")
        new_subedges = list()
        progress = ProgressBar(len(dao.subedges))
        for subedge in dao.subedges:
            if subedge.edge.filterSubEdge(subedge):
                subedge.pruneable = True
            else:
                new_subedges.append(subedge)
            progress.update()
        dao.subedges = new_subedges

        progress.end()
예제 #12
0
    if right_side_m > 0 and right_side_c > right_side_m:
        return False

    visited[(m, c, s)] = True

    if s == 1:
        op = -1
    else:
        op = 1

    solved = False
    for i in range(5):
        next_m, next_c, next_side = m + op * options[i][0], c + op * options[
            i][1], int(not s)

        if is_valid(next_m, next_c):

            if (next_m, next_c, next_side) not in visited:
                solved = (solved or dfs(
                    m=next_m, c=next_c, s=next_side, level=level + 1))

                if solved:
                    return True
    return solved


if (dfs(m=3, c=3, s=1, level=0)):
    print("SOlution Found")
    # Save recursion tree to a file
    vs.make_animation("missionaries.gif", delay=2)
def main():
    amount = 5
    coins = [1, 2, 5]
    print(f(coins=coins, amount=amount, n=len(coins)))
    vs.make_animation("coin_change.gif", delay=3)
예제 #14
0
def main():
    # Call function
    print(fib(n=6))
    # Save recursion tree to a file
    vs.make_animation("fibonacci.gif", delay=2)
from visualiser.visualiser import Visualiser as vs
"""
Problem Link: https://stackoverflow.com/questions/33808653/recursion-tree-with-fibonacci-python/60126306#60126306
"""


@vs(node_properties_kwargs={
    "shape": "record",
    "color": "#f57542",
    "style": "filled",
    "fillcolor": "grey"
})
def binary(length, outstr=""):
    if len(outstr) == length:
        print(outstr)
    else:
        for i in ["0", "1"]:
            binary(length=length, outstr=outstr + i)


binary(length=3, outstr="")
vs.make_animation("binary_string.gif", delay=2)
class TestVisualiser(unittest.TestCase):
    """
    Testcase for the Visualiser Class
    """
    @classmethod
    def setUpClass(self):
        """
        Sets up the class. The data only has to be read in once, so this is done in the class setup method.
        """
        # TODO: Remove warn ngs filter when migrating to geopandas > 0.7.0 !
        warnings.simplefilter('ignore', category=FutureWarning)
        warnings.simplefilter('ignore', category=DeprecationWarning)

        static_data = StaticDataReader('data/berlin_bounds.poly',
                                       'data/berlin_stops.geojson')
        bounding_box_tuple = (13.34014892578125, 52.52791908000258,
                              13.506317138671875, 52.562995039558004)
        simulator = Simulator(bounding_box=bounding_box_tuple)
        simulation_results = simulator.simulate(number_of_requests=6)

        self.visualiser = Visualiser(
            bounding_box=BoundingBox(bounding_box_tuple),
            simulation_results=simulation_results,
            static_data=static_data,
            static_path='webapp/static')

    def setUp(self):
        pass

    def test_generate_overview_figure(self):
        """
        Asserts a overview figure is generated after calling the function.
        """
        self.visualiser.generate_overview_figure()

        self.assertTrue(
            isfile(
                f"{self.visualiser.static_path}/{self.visualiser.id}_overview_plot.png"
            ))

    def test_generate_closeup_figure(self):
        """
        Asserts a closeup figure is generated after calling the function.
        """
        self.visualiser.generate_closeup_figure()

        self.assertTrue(
            isfile(
                f"{self.visualiser.static_path}/{self.visualiser.id}_closeup_plot.png"
            ))

    def test_generate_gmap(self):
        """
        Asserts a html map is generated after calling the function.
        """
        self.visualiser.generate_gmap()

        self.assertTrue(
            isfile(
                f"{self.visualiser.static_path}/{self.visualiser.id}_map.html")
        )

    def tearDown(self):
        pass

    if __name__ == "__main__":
        unittest.main()
예제 #17
0
def main():
    # Call function
    print(max_revenue(5,prices))
    # Save recursion tree to a file
    vs.make_animation("fibonacci.gif", delay=1)
예제 #18
0
def main():
    # Call function
    print(lis([-4, 10, 3, 7, 15], 0, -1))
    # Save recursion tree to a file
    vs.make_animation("lis.gif", delay=2)
예제 #19
0
from visualiser.visualiser import Visualiser as vs
"""
    Given an array of numbers, find all the subsets:
    eg: nums = [1, 2, 3]
    Output:
        [[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2 , 1]]
    You can find my explanation here: https://qr.ae/TWHmsi 
"""

subsets = []


@vs(ignore_args=["nums"], show_return_value=False, show_argument_name=False)
def f(nums, i, current_subset):
    # If no more elements left
    if i == 0:
        subsets.append(current_subset)
        return
    # Exclude Current element
    f(nums=nums, i=i - 1, current_subset=current_subset)

    # Include current element
    f(nums=nums, i=i - 1, current_subset=current_subset + [nums[i - 1]])


if __name__ == "__main__":
    nums = [1, 2, 3]
    f(nums=nums, i=len(nums), current_subset=[])
    # Save recursion tree to a file
    vs.make_animation("subset.gif", delay=3)