Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moved to pyproject + development workflow + type checking #18

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/Development
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Development

on:
push:
branches:
- master
pull_request:
types: [opened, synchronize]

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
cache-dependency-path: pyproject.toml
- uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-test-v03
- name: Install dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -e .[test]
- name: Lint with ruff
run: |
# stop the build if there are Python syntax errors or undefined names
ruff --format=github --select=E9,F63,F7,F82 --target-version=py37 .
# default set of ruff rules with GitHub Annotations
ruff --format=github --target-version=py37 .
- name: Test with pytest
run: |
pytest
12 changes: 5 additions & 7 deletions foodwebviz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
"""

# Import foodwebviz objects
from foodwebviz.io import * # noqa: F401,F403
from foodwebviz.utils import * # noqa: F401,F403
from foodwebviz.visualization import * # noqa: F401,F403
from foodwebviz.foodweb import * # noqa: F401,F403
from foodwebviz.create_animated_food_web import * # noqa: F401,F403
from foodwebviz.io import *
from foodwebviz.utils import *
from foodwebviz.visualization import *
from foodwebviz.foodweb import *
from foodwebviz.create_animated_food_web import *


__version__ = "0.1"
44 changes: 34 additions & 10 deletions foodwebviz/create_animated_food_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,33 @@
The master functions for animation.
@author: Mateusz
"""
from __future__ import annotations

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from typing import Callable, Optional, TYPE_CHECKING

from foodwebviz.animation.network_image import NetworkImage
from foodwebviz.animation import animation_utils

if TYPE_CHECKING:
import foodwebviz as fw


__all__ = [
'animate_foodweb',
'animate_foodweb'
]


def _run_animation(filename, func, frames, interval, fig=None, figsize=(6.5, 6.5), fps=None, dpi=None):
def _run_animation(filename: str,
func: Callable[[int], None],
frames: int,
interval: float,
fig: Optional[tuple[float, float]] = None,
figsize: tuple[float, float] = (6.5, 6.5),
fps: Optional[int] = None,
dpi: Optional[float] = None) -> None:
r""" Creates an animated GIF of a matplotlib.

Parameters
Expand Down Expand Up @@ -53,16 +66,26 @@ def forward(frame):
if fig is None:
fig = plt.figure(figsize=figsize)

forward.first = True
anim = animation.FuncAnimation(fig, forward, frames=frames, interval=interval)
forward.first = True # type: ignore
anim = animation.FuncAnimation(
fig, forward, frames=frames, interval=interval)
anim.save(filename, writer='imagemagick', fps=fps, dpi=dpi)


def animate_foodweb(foodweb, gif_file_out, fps=10, anim_len=1, trails=1,
min_node_radius=0.5, min_part_num=1,
max_part_num=20, map_fun=np.sqrt, include_imports=True, include_exports=False,
cmap=plt.cm.get_cmap('viridis'), max_luminance=0.85,
particle_size=8):
def animate_foodweb(foodweb: fw.FoodWeb,
gif_file_out: str,
fps: int = 10,
anim_len: int = 1,
trails: int = 1,
min_node_radius: float = 0.5,
min_part_num: int = 1,
max_part_num: int = 20,
map_fun: Callable = np.sqrt,
include_imports: bool = True,
include_exports: bool = False,
cmap: plt.Colormap = plt.cm.get_cmap('viridis'),
max_luminance: float = 0.85,
particle_size: int = 8) -> None:
'''foodweb_animation creates a GIF animation saved as gif_file_out based on the food web
provided as a SCOR file scor_file_in. The canvas size in units relevant
to further parameters is [0,100]x[0,100].
Expand Down Expand Up @@ -139,5 +162,6 @@ def animate_frame(frame):
frames=fps * anim_len, # number of frames,
interval=interval,
figsize=(20, 20),
dpi=100 + 1.75 * len(network_image.nodes), # adapt the resolution to the number of nodes
# adapt the resolution to the number of nodes
dpi=100 + 1.75 * len(network_image.nodes),
fps=fps)
61 changes: 38 additions & 23 deletions foodwebviz/foodweb.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'''Class for foodwebs.'''
import pandas as pd
import networkx as nx

import foodwebviz as fw
from .normalization import normalization_factory



__all__ = [
'FoodWeb'
]
Expand All @@ -16,7 +18,7 @@ class FoodWeb(object):
It stores species and flows between them with additional data like Biomass.
'''

def __init__(self, title, node_df, flow_matrix):
def __init__(self, title: str, node_df: pd.DataFrame, flow_matrix: pd.DataFrame) -> None:
'''Initialize a foodweb with title, nodes and flow matrix.
Parameters
----------
Expand Down Expand Up @@ -44,9 +46,11 @@ def __init__(self, title, node_df, flow_matrix):
self.node_df['TrophicLevel'] = fw.calculate_trophic_levels(self)
self._graph = self._init_graph()

def _init_graph(self):
def _init_graph(self) -> nx.DiGraph:
'''Returns networkx.DiGraph initialized using foodweb's flow matrix.'''
graph = nx.from_pandas_adjacency(self.get_flow_matrix(boundary=True), create_using=nx.DiGraph)
graph = nx.from_pandas_adjacency(
df=self.get_flow_matrix(boundary=True),
create_using=nx.DiGraph)
nx.set_node_attributes(graph, self.node_df.to_dict(orient='index'))

exclude_edges = []
Expand All @@ -57,13 +61,16 @@ def _init_graph(self):
graph.remove_edges_from(exclude_edges)
return graph

def get_diet_matrix(self):
def get_diet_matrix(self) -> pd.DataFrame:
'''Returns a matrix of system flows express as diet proportions=
=fraction of node inflows this flow contributes'''
return self.flow_matrix.div(self.flow_matrix.sum(axis=0), axis=1).fillna(0.0)

def get_graph(self, boundary=False, mark_alive_nodes=False, normalization=None,
no_flows_to_detritus=False):
def get_graph(self,
boundary: bool = False,
mark_alive_nodes: bool = False,
normalization: str = 'linear',
no_flows_to_detritus: bool = False) -> nx.DiGraph:
'''Returns foodweb as networkx.SubGraph View fo networkx.DiGraph.

Parameters
Expand All @@ -90,16 +97,23 @@ def get_graph(self, boundary=False, mark_alive_nodes=False, normalization=None,
exclude_edges = []
if no_flows_to_detritus:
not_alive_nodes = self.node_df[~self.node_df.IsAlive].index.values
exclude_edges = [edge for edge in self._graph.edges() if edge[1] in not_alive_nodes]
exclude_edges = [
edge for edge in self._graph.edges() if edge[1] in not_alive_nodes]

g = nx.restricted_view(self._graph.copy(), exclude_nodes, exclude_edges)
g = nx.restricted_view(
G=self._graph.copy(),
nodes=exclude_nodes,
edges=exclude_edges)
if mark_alive_nodes:
g = nx.relabel_nodes(g, fw.is_alive_mapping(self))
g = normalization_factory(g, norm_type=normalization)
return g

def get_flows(self, boundary=False, mark_alive_nodes=False, normalization=None,
no_flows_to_detritus=False):
def get_flows(self,
boundary: bool = False,
mark_alive_nodes: bool = False,
normalization: str = 'linear',
no_flows_to_detritus: bool = False) -> list[tuple[str, str, dict[str, float]]]:
'''Returns a list of all flows within foodweb.

Parameters
Expand All @@ -126,7 +140,7 @@ def get_flows(self, boundary=False, mark_alive_nodes=False, normalization=None,
return (self.get_graph(boundary, mark_alive_nodes, normalization, no_flows_to_detritus)
.edges(data=True))

def get_flow_matrix(self, boundary=False, to_alive_only=False):
def get_flow_matrix(self, boundary: bool = False, to_alive_only: bool = False) -> pd.DataFrame:
'''Returns the flow (adjacency) matrix.

Parameters
Expand All @@ -153,30 +167,36 @@ def get_flow_matrix(self, boundary=False, to_alive_only=False):
return flow_matrix

flow_matrix_with_boundary = self.flow_matrix.copy()
flow_matrix_with_boundary.loc['Import'] = self.node_df.Import.to_dict()
flow_matrix_with_boundary.loc['Export'] = self.node_df.Export.to_dict()
flow_matrix_with_boundary.loc['Respiration'] = self.node_df.Respiration.to_dict()
flow_matrix_with_boundary.loc['Import'] = self.node_df.Import.to_dict() # type: ignore
flow_matrix_with_boundary.loc['Export'] = self.node_df.Export.to_dict() # type: ignore
flow_matrix_with_boundary.loc['Respiration'] = self.node_df.Respiration.to_dict() # type: ignore
return (
flow_matrix_with_boundary
.join(self.node_df.Import)
.join(self.node_df.Export)
.join(self.node_df.Respiration)
.fillna(0.0))

def get_links_number(self):
def get_links_number(self) -> int:
'''Returns the number of nonzero flows.
'''
return self.get_graph(False).number_of_edges()

def get_flow_sum(self):
def get_flow_sum(self) -> pd.Series:
'''Returns the sum of all flows.
'''
return self.get_flow_matrix(boundary=True).sum()

def get_norm_node_prop(self):
num_node_prop = self.node_df[["Biomass", "Import", "Export", "Respiration"]]
def get_norm_node_prop(self) -> pd.DataFrame:
cols = ["Biomass", "Import", "Export", "Respiration"]
num_node_prop = self.node_df[cols]
return num_node_prop.div(num_node_prop.sum(axis=0), axis=1)

def get_outflows_to_living(self) -> pd.Series:
# node's system outflows to living
# TODO doc
return self.flow_matrix[self.node_df[self.node_df.IsAlive].index].sum(axis='columns')

def __str__(self):
return f'''
{self.title}\n
Expand All @@ -188,8 +208,3 @@ def __str__(self):
{self.node_df["Respiration"]}\n
{self.node_df["TrophicLevel"]}\n
'''

def get_outflows_to_living(self):
# node's system outflows to living
# TODO doc
return self.flow_matrix[self.node_df[self.node_df.IsAlive].index].sum(axis='columns')