Exemple #1
0
    def test_endpoints(self):
        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0.5, 0.9])
        self.assertEqual(t.start_node(), 0)
        self.assertEqual(t.end_node(), 3)

        # Auto sorting.
        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0., 0.1])
        self.assertEqual(t.start_node(), 2)

        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0., 0.1])
        self.assertEqual(t.end_node(), 1)
Exemple #2
0
    def test_contains(self):
        t = Trajectory([1, 2, 3, 2, 3, 3], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6])

        self.assertTrue(1 in t)
        self.assertTrue(3 in t)
        self.assertFalse(0.2 in t)
        self.assertFalse(5 in t)
Exemple #3
0
    def test_init(self):
        # ID
        id = random.randint(0, 1000)
        t = Trajectory([0], id=id)
        self.assertEqual(t.id, id)

        # Invalid
        self.assertRaises(ValueError, Trajectory, [1, 2], [1, 2, 3])
Exemple #4
0
    def test_fpt(self):
        t = Trajectory([1, 2, 3, 2, 3, 3], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
        self.assertEqual(t.fpt(3), 0.3)

        t = Trajectory([1, 2, 2, 3, 3, 3], [0.1, 0.4, 0.2, 0.6, 0.5, 0.3])
        self.assertEqual(t.fpt(3), 0.3)
        self.assertTrue(np.isnan(t.fpt(1000)))
Exemple #5
0
    def test_append(self):
        t = Trajectory([1, 2])
        t.append(3)
        t.append(4)
        self.assertSequenceEqual(t.nodes, [1, 2, 3, 4])
        self.assertSequenceEqual(t.times, [0, 1, 2, 3])

        t = Trajectory([1, 2], [0.1, 0.2])
        t.append(3, 0.3)
        self.assertSequenceEqual(t.nodes, [1, 2, 3])
        self.assertSequenceEqual(t.times, [.1, .2, .3])
Exemple #6
0
nodes = [
    node for node, dist in nx.shortest_path_length(graph, 0).items()
    if dist == 15
]
fig, ax = er.plot.graph.structure(graph)
er.plot.graph.node_label(ax, graph, 0, 'S')
for node in nodes:
    er.plot.graph.node_label(ax, graph, node)
fig.savefig(
    FIGURES_PATH.joinpath(f'{GRAPH}_kymograph_nodes_at_distance_15.svg'))

# %% Switching network
# ====================

path = Trajectory(nx.shortest_path(graph, SOURCE, TARGET))

for tau in TAUS:
    trajs = load_data(
        f'trajs/{GRAPH}_SwitchingNetwork_ExponentialWalker_tau{tau:e}_N{NUM_TRAJS}_max_time{MAX_TIME}',
        suffix='.parquet')
    fig_path, fig_avg = create_kymographs(trajs, path, graph)
    fig_path.savefig(
        FIGURES_PATH.joinpath(f'{GRAPH}_kymograph_tau{tau:.2f}_path.svg'))
    fig_avg.savefig(
        FIGURES_PATH.joinpath(f'{GRAPH}_kymograph_tau{tau:.2f}_avg.svg'))

# %% Undirected network
# =====================

trajs = load_data(
Exemple #7
0
    def test_time(self):
        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0.5, 0.9])
        self.assertEqual(t.time(), 0.9)

        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0., 0.1])
        self.assertEqual(t.time(), 0.3)
Exemple #8
0
    def test_duration(self):
        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0.5, 0.9])
        self.assertEqual(t.duration(), 0.9 - 0.2)

        t = Trajectory([0, 1, 2, 3], [0.2, 0.3, 0., 0.1])
        self.assertEqual(t.duration(), 0.3)
Exemple #9
0
 def test_traps(self):
     t = Trajectory([1, 2, 2, 3, 4, 4, 4, 5])
     self.assertSequenceEqual(t.traps(), [2, 4, 4])
Exemple #10
0
 def test_edges(self):
     t = Trajectory([1, 2, 3, 3, 4])
     self.assertSequenceEqual(t.edges(), [(1, 2), (2, 3), (3, 3), (3, 4)])
Exemple #11
0
    def test_times(self):
        t = Trajectory([10, 21, 34])
        self.assertSequenceEqual(t.times, [0, 1, 2])

        t = Trajectory([10, 21, 34], [0.1, 0.2, 0.3])
        self.assertSequenceEqual(t.times, [0.1, 0.2, 0.3])
Exemple #12
0
    def test_length(self):
        t = Trajectory([1])
        self.assertEqual(len(t), 0)

        t = Trajectory([0, 1, 2, 3])
        self.assertEqual(len(t), 3)
Exemple #13
0
    def trajectories_to_target(self,
                               num_walkers,
                               target,
                               keep=None,
                               progress=True):
        """Simulates the walkers motion until they hit a given target.

        Parameters
        ----------
        num_walkers : int
            The number of walkers to simulate.
        target :
            The target node label.
        keep : int
            The number of trajectories to keep (sorted by arrival time).
            For example, if `keep` is 10 only the trajectories of the first
            10 walkers to arrive at the target will be returned. If set to
            `None`, all the trajectories will be returned.

        Returns
        -------
        data : pandas.Dataframe
            A :class:`pandas.DataFrame` containing the trajectories.
        """
        if keep is None:
            keep = num_walkers

        network = self.network
        walkers = np.array([copy(self.walker) for _ in range(num_walkers)])

        active_idx = set(range(num_walkers))
        times = np.array([w.time for w in walkers], dtype=np.float)

        paths = np.array([
            Trajectory([w.node], times=[w.time], id=i)
            for i, w in enumerate(walkers)
        ])

        sim_time = 0.
        arrival_times = np.full_like(walkers, fill_value=np.inf)
        steps = 0

        while True:
            completed = set()
            for id in active_idx:
                walker = walkers[id]

                node, times[id] = walker.step(network)
                paths[id].append(node, times[id])

                if node == target:
                    completed.add(id)
                    arrival_times[id] = times[id]

            active_idx.difference_update(completed)

            if active_idx:
                sim_time = times[list(active_idx)].min()
            else:
                # All walkers arrived
                break

            if np.sum(arrival_times < sim_time) >= keep:
                # First N walkers have arrived
                break

            # Clear memory
            if steps % 10000 == 0 and hasattr(network, 'clear_memory'):
                network.clear_memory(sim_time)

            steps += 1

        # Simulation ended, now retrieve the trajectories.
        idx = np.argsort(arrival_times)[:keep]
        data = pd.concat([path.to_dataframe() for path in paths[idx]])

        return data
Exemple #14
0
    def trajectories(self,
                     num_walkers,
                     max_time,
                     start_nodes=None,
                     progress=True):
        """Simulates the walkers motion for a limited time.

        Parameters
        ----------
        num_walkers : int
            The number of walkers to simulate.
        max_time : float
            The time at which the simulation will be interrupted.
        progress : bool
            Whether to show the progress bar during the simulation.

        Returns
        -------
        trajectories : pd.DataFrame
            A :class:`pandas.DataFrame` containing the trajectories.
        """
        network = self.network
        walkers = [copy(self.walker) for _ in range(num_walkers)]
        if start_nodes is not None:
            if len(start_nodes) != len(walkers):
                raise Exception(
                    "Number of starting nodes must be equal to walkers")
            for i, node in enumerate(start_nodes):
                walkers[i].start = node
                walkers[i].node = node

        times = np.array([w.time for w in walkers], dtype=np.float)

        trajs = [
            Trajectory([w.node], [w.time], id=k) for k, w in enumerate(walkers)
        ]
        sim_time = 0
        steps = 0

        if progress:
            bar = tqdm(total=max_time)

        while sim_time < max_time:
            for id, walker in enumerate(walkers):
                if walker.time >= max_time:
                    continue

                node, times[id] = walker.step(network)
                trajs[id].append(node, times[id])

            steps += 1
            sim_time = times.min()

            if progress:
                bar.n = round(sim_time, 2)
                bar.update(0)

            # Clear memory
            if steps % 10000 == 0 and getattr(network, 'memory', False):
                network.clear_memory(sim_time)

        return pd.concat([traj.to_dataframe() for traj in trajs])