repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
mtenv | mtenv-main/mtenv/utils/types.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Any, Dict, Tuple, Union
import numpy as np
TaskObsType = Union[str, int, float, np.ndarray]
ActionType = Union[str, int, float, np.ndarray]
EnvObsType = Union[np.ndarray]
ObsType = Dict[str, Union[EnvObsType, TaskObsType]]
RewardType = float
DoneType = bool
InfoType = Dict[str, Any]
StepReturnType = Tuple[ObsType, RewardType, DoneType, InfoType]
EnvStepReturnType = Tuple[EnvObsType, RewardType, DoneType, InfoType]
TaskStateType = Any
| 530 | 32.1875 | 70 | py |
mtenv | mtenv-main/mtenv/utils/seeding.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Optional, Tuple
from gym.utils import seeding
from numpy.random import RandomState
def np_random(seed: Optional[int]) -> Tuple[RandomState, int]:
"""Set the seed for numpy's random generator.
Args:
seed (Optional[int]):
Returns:
Tuple[RandomState, int]: Returns a tuple of random state and seed.
"""
rng, seed = seeding.np_random(seed)
assert isinstance(seed, int)
return rng, seed
| 521 | 25.1 | 74 | py |
mtenv | mtenv-main/mtenv/utils/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
| 71 | 35 | 70 | py |
mtenv | mtenv-main/local_dm_control_suite/base.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Base class for tasks in the Control Suite."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from dm_control import mujoco
from dm_control.rl import control
import numpy as np
class Task(control.Task):
"""Base class for tasks in the Control Suite.
Actions are mapped directly to the states of MuJoCo actuators: each element of
the action array is used to set the control input for a single actuator. The
ordering of the actuators is the same as in the corresponding MJCF XML file.
Attributes:
random: A `numpy.random.RandomState` instance. This should be used to
generate all random variables associated with the task, such as random
starting states, observation noise* etc.
*If sensor noise is enabled in the MuJoCo model then this will be generated
using MuJoCo's internal RNG, which has its own independent state.
"""
def __init__(self, random=None):
"""Initializes a new continuous control task.
Args:
random: Optional, either a `numpy.random.RandomState` instance, an integer
seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
if not isinstance(random, np.random.RandomState):
random = np.random.RandomState(random)
self._random = random
self._visualize_reward = False
@property
def random(self):
"""Task-specific `numpy.random.RandomState` instance."""
return self._random
def action_spec(self, physics):
"""Returns a `BoundedArraySpec` matching the `physics` actuators."""
return mujoco.action_spec(physics)
def initialize_episode(self, physics):
"""Resets geom colors to their defaults after starting a new episode.
Subclasses of `base.Task` must delegate to this method after performing
their own initialization.
Args:
physics: An instance of `mujoco.Physics`.
"""
self.after_step(physics)
def before_step(self, action, physics):
"""Sets the control signal for the actuators to values in `action`."""
# Support legacy internal code.
action = getattr(action, "continuous_actions", action)
physics.set_control(action)
def after_step(self, physics):
"""Modifies colors according to the reward."""
if self._visualize_reward:
reward = np.clip(self.get_reward(physics), 0.0, 1.0)
_set_reward_colors(physics, reward)
@property
def visualize_reward(self):
return self._visualize_reward
@visualize_reward.setter
def visualize_reward(self, value):
if not isinstance(value, bool):
raise ValueError("Expected a boolean, got {}.".format(type(value)))
self._visualize_reward = value
_MATERIALS = ["self", "effector", "target"]
_DEFAULT = [name + "_default" for name in _MATERIALS]
_HIGHLIGHT = [name + "_highlight" for name in _MATERIALS]
def _set_reward_colors(physics, reward):
"""Sets the highlight, effector and target colors according to the reward."""
assert 0.0 <= reward <= 1.0
colors = physics.named.model.mat_rgba
default = colors[_DEFAULT]
highlight = colors[_HIGHLIGHT]
blend_coef = reward ** 4 # Better color distinction near high rewards.
colors[_MATERIALS] = blend_coef * highlight + (1.0 - blend_coef) * default
| 4,139 | 35.637168 | 84 | py |
mtenv | mtenv-main/local_dm_control_suite/explore.py | # Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Control suite environments explorer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
from dm_control import suite
from dm_control.suite.wrappers import action_noise
from six.moves import input
from dm_control import viewer
_ALL_NAMES = [".".join(domain_task) for domain_task in suite.ALL_TASKS]
flags.DEFINE_enum(
"environment_name",
None,
_ALL_NAMES,
"Optional 'domain_name.task_name' pair specifying the "
"environment to load. If unspecified a prompt will appear to "
"select one.",
)
flags.DEFINE_bool("timeout", True, "Whether episodes should have a time limit.")
flags.DEFINE_bool(
"visualize_reward",
True,
"Whether to vary the colors of geoms according to the " "current reward value.",
)
flags.DEFINE_float(
"action_noise",
0.0,
"Standard deviation of Gaussian noise to apply to actions, "
"expressed as a fraction of the max-min range for each "
"action dimension. Defaults to 0, i.e. no noise.",
)
FLAGS = flags.FLAGS
def prompt_environment_name(prompt, values):
environment_name = None
while not environment_name:
environment_name = input(prompt)
if not environment_name or values.index(environment_name) < 0:
print('"%s" is not a valid environment name.' % environment_name)
environment_name = None
return environment_name
def main(argv):
del argv
environment_name = FLAGS.environment_name
if environment_name is None:
print("\n ".join(["Available environments:"] + _ALL_NAMES))
environment_name = prompt_environment_name(
"Please select an environment name: ", _ALL_NAMES
)
index = _ALL_NAMES.index(environment_name)
domain_name, task_name = suite.ALL_TASKS[index]
task_kwargs = {}
if not FLAGS.timeout:
task_kwargs["time_limit"] = float("inf")
def loader():
env = suite.load(
domain_name=domain_name, task_name=task_name, task_kwargs=task_kwargs
)
env.task.visualize_reward = FLAGS.visualize_reward
if FLAGS.action_noise > 0:
env = action_noise.Wrapper(env, scale=FLAGS.action_noise)
return env
viewer.launch(loader)
if __name__ == "__main__":
app.run(main)
| 3,023 | 30.5 | 84 | py |
mtenv | mtenv-main/local_dm_control_suite/cartpole.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Cartpole domain."""
from __future__ import absolute_import, division, print_function
import collections
import numpy as np
from dm_control import mujoco
from dm_control.rl import control
from dm_control.utils import containers, rewards
from . import base, common
from lxml import etree
from six.moves import range
_DEFAULT_TIME_LIMIT = 10
SUITE = containers.TaggedTasks()
def get_model_and_assets(num_poles=1, xml_file_id=None):
"""Returns a tuple containing the model XML string and a dict of assets."""
return _make_model(num_poles, xml_file_id), common.ASSETS
@SUITE.add("benchmarking")
def balance(
time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None,
):
"""Returns the Cartpole Balance task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Balance(swing_up=False, sparse=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add("benchmarking")
def balance_sparse(
time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns the sparse reward variant of the Cartpole Balance task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Balance(swing_up=False, sparse=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add("benchmarking")
def swingup(
time_limit=_DEFAULT_TIME_LIMIT,
xml_file_id=None,
random=None,
environment_kwargs=None,
):
"""Returns the Cartpole Swing-Up task."""
physics = Physics.from_xml_string(*get_model_and_assets(xml_file_id=xml_file_id))
task = Balance(swing_up=True, sparse=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add("benchmarking")
def swingup_sparse(
time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns the sparse reward variant of teh Cartpole Swing-Up task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Balance(swing_up=True, sparse=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add()
def two_poles(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Cartpole Balance task with two poles."""
physics = Physics.from_xml_string(*get_model_and_assets(num_poles=2))
task = Balance(swing_up=True, sparse=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add()
def three_poles(
time_limit=_DEFAULT_TIME_LIMIT,
random=None,
num_poles=3,
sparse=False,
environment_kwargs=None,
):
"""Returns the Cartpole Balance task with three or more poles."""
physics = Physics.from_xml_string(*get_model_and_assets(num_poles=num_poles))
task = Balance(swing_up=True, sparse=sparse, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
def _make_model(n_poles, xml_file_id=None):
"""Generates an xml string defining a cart with `n_poles` bodies."""
if xml_file_id is not None:
filename = f"cartpole_{xml_file_id}.xml"
print(filename)
else:
filename = f"cartpole.xml"
xml_string = common.read_model(filename)
if n_poles == 1:
return xml_string
mjcf = etree.fromstring(xml_string)
parent = mjcf.find("./worldbody/body/body") # Find first pole.
# Make chain of poles.
for pole_index in range(2, n_poles + 1):
child = etree.Element(
"body", name="pole_{}".format(pole_index), pos="0 0 1", childclass="pole"
)
etree.SubElement(child, "joint", name="hinge_{}".format(pole_index))
etree.SubElement(child, "geom", name="pole_{}".format(pole_index))
parent.append(child)
parent = child
# Move plane down.
floor = mjcf.find("./worldbody/geom")
floor.set("pos", "0 0 {}".format(1 - n_poles - 0.05))
# Move cameras back.
cameras = mjcf.findall("./worldbody/camera")
cameras[0].set("pos", "0 {} 1".format(-1 - 2 * n_poles))
cameras[1].set("pos", "0 {} 2".format(-2 * n_poles))
return etree.tostring(mjcf, pretty_print=True)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Cartpole domain."""
def cart_position(self):
"""Returns the position of the cart."""
return self.named.data.qpos["slider"][0]
def angular_vel(self):
"""Returns the angular velocity of the pole."""
return self.data.qvel[1:]
def pole_angle_cosine(self):
"""Returns the cosine of the pole angle."""
return self.named.data.xmat[2:, "zz"]
def bounded_position(self):
"""Returns the state, with pole angle split into sin/cos."""
return np.hstack(
(self.cart_position(), self.named.data.xmat[2:, ["zz", "xz"]].ravel())
)
class Balance(base.Task):
"""A Cartpole `Task` to balance the pole.
State is initialized either close to the target configuration or at a random
configuration.
"""
_CART_RANGE = (-0.25, 0.25)
_ANGLE_COSINE_RANGE = (0.995, 1)
def __init__(self, swing_up, sparse, random=None):
"""Initializes an instance of `Balance`.
Args:
swing_up: A `bool`, which if `True` sets the cart to the middle of the
slider and the pole pointing towards the ground. Otherwise, sets the
cart to a random position on the slider and the pole to a random
near-vertical position.
sparse: A `bool`, whether to return a sparse or a smooth reward.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._sparse = sparse
self._swing_up = swing_up
super(Balance, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Initializes the cart and pole according to `swing_up`, and in both cases
adds a small random initial velocity to break symmetry.
Args:
physics: An instance of `Physics`.
"""
nv = physics.model.nv
if self._swing_up:
physics.named.data.qpos["slider"] = 0.01 * self.random.randn()
physics.named.data.qpos["hinge_1"] = np.pi + 0.01 * self.random.randn()
physics.named.data.qpos[2:] = 0.1 * self.random.randn(nv - 2)
else:
physics.named.data.qpos["slider"] = self.random.uniform(-0.1, 0.1)
physics.named.data.qpos[1:] = self.random.uniform(-0.034, 0.034, nv - 1)
physics.named.data.qvel[:] = 0.01 * self.random.randn(physics.model.nv)
super(Balance, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of the (bounded) physics state."""
obs = collections.OrderedDict()
obs["position"] = physics.bounded_position()
obs["velocity"] = physics.velocity()
return obs
def _get_reward(self, physics, sparse):
if sparse:
cart_in_bounds = rewards.tolerance(
physics.cart_position(), self._CART_RANGE
)
angle_in_bounds = rewards.tolerance(
physics.pole_angle_cosine(), self._ANGLE_COSINE_RANGE
).prod()
return cart_in_bounds * angle_in_bounds
else:
upright = (physics.pole_angle_cosine() + 1) / 2
centered = rewards.tolerance(physics.cart_position(), margin=2)
centered = (1 + centered) / 2
small_control = rewards.tolerance(
physics.control(), margin=1, value_at_margin=0, sigmoid="quadratic"
)[0]
small_control = (4 + small_control) / 5
small_velocity = rewards.tolerance(physics.angular_vel(), margin=5).min()
small_velocity = (1 + small_velocity) / 2
return upright.mean() * small_control * small_velocity * centered
def get_reward(self, physics):
"""Returns a sparse or a smooth reward, as specified in the constructor."""
return self._get_reward(physics, sparse=self._sparse)
| 9,502 | 36.561265 | 85 | py |
mtenv | mtenv-main/local_dm_control_suite/humanoid.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Humanoid Domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
_DEFAULT_TIME_LIMIT = 25
_CONTROL_TIMESTEP = 0.025
# Height of head above which stand reward is 1.
_STAND_HEIGHT = 1.4
# Horizontal speeds above which move reward is 1.
_WALK_SPEED = 1
_RUN_SPEED = 10
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("humanoid.xml"), common.ASSETS
@SUITE.add("benchmarking")
def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Stand task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Humanoid(move_speed=0, pure_state=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add("benchmarking")
def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Walk task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Humanoid(move_speed=_WALK_SPEED, pure_state=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add("benchmarking")
def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Run task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Humanoid(move_speed=_RUN_SPEED, pure_state=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add()
def run_pure_state(
time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns the Run task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Humanoid(move_speed=_RUN_SPEED, pure_state=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Walker domain."""
def torso_upright(self):
"""Returns projection from z-axes of torso to the z-axes of world."""
return self.named.data.xmat["torso", "zz"]
def head_height(self):
"""Returns the height of the torso."""
return self.named.data.xpos["head", "z"]
def center_of_mass_position(self):
"""Returns position of the center-of-mass."""
return self.named.data.subtree_com["torso"].copy()
def center_of_mass_velocity(self):
"""Returns the velocity of the center-of-mass."""
return self.named.data.sensordata["torso_subtreelinvel"].copy()
def torso_vertical_orientation(self):
"""Returns the z-projection of the torso orientation matrix."""
return self.named.data.xmat["torso", ["zx", "zy", "zz"]]
def joint_angles(self):
"""Returns the state without global orientation or position."""
return self.data.qpos[7:].copy() # Skip the 7 DoFs of the free root joint.
def extremities(self):
"""Returns end effector positions in egocentric frame."""
torso_frame = self.named.data.xmat["torso"].reshape(3, 3)
torso_pos = self.named.data.xpos["torso"]
positions = []
for side in ("left_", "right_"):
for limb in ("hand", "foot"):
torso_to_limb = self.named.data.xpos[side + limb] - torso_pos
positions.append(torso_to_limb.dot(torso_frame))
return np.hstack(positions)
class Humanoid(base.Task):
"""A humanoid task."""
def __init__(self, move_speed, pure_state, random=None):
"""Initializes an instance of `Humanoid`.
Args:
move_speed: A float. If this value is zero, reward is given simply for
standing up. Otherwise this specifies a target horizontal velocity for
the walking task.
pure_state: A bool. Whether the observations consist of the pure MuJoCo
state or includes some useful features thereof.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._move_speed = move_speed
self._pure_state = pure_state
super(Humanoid, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Args:
physics: An instance of `Physics`.
"""
# Find a collision-free random initial configuration.
penetrating = True
while penetrating:
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
# Check for collisions.
physics.after_reset()
penetrating = physics.data.ncon > 0
super(Humanoid, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns either the pure state or a set of egocentric features."""
obs = collections.OrderedDict()
if self._pure_state:
obs["position"] = physics.position()
obs["velocity"] = physics.velocity()
else:
obs["joint_angles"] = physics.joint_angles()
obs["head_height"] = physics.head_height()
obs["extremities"] = physics.extremities()
obs["torso_vertical"] = physics.torso_vertical_orientation()
obs["com_velocity"] = physics.center_of_mass_velocity()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
standing = rewards.tolerance(
physics.head_height(),
bounds=(_STAND_HEIGHT, float("inf")),
margin=_STAND_HEIGHT / 4,
)
upright = rewards.tolerance(
physics.torso_upright(),
bounds=(0.9, float("inf")),
sigmoid="linear",
margin=1.9,
value_at_margin=0,
)
stand_reward = standing * upright
small_control = rewards.tolerance(
physics.control(), margin=1, value_at_margin=0, sigmoid="quadratic"
).mean()
small_control = (4 + small_control) / 5
if self._move_speed == 0:
horizontal_velocity = physics.center_of_mass_velocity()[[0, 1]]
dont_move = rewards.tolerance(horizontal_velocity, margin=2).mean()
return small_control * stand_reward * dont_move
else:
com_velocity = np.linalg.norm(physics.center_of_mass_velocity()[[0, 1]])
move = rewards.tolerance(
com_velocity,
bounds=(self._move_speed, float("inf")),
margin=self._move_speed,
value_at_margin=0,
sigmoid="linear",
)
move = (5 * move + 1) / 6
return small_control * stand_reward * move
| 8,547 | 34.915966 | 85 | py |
mtenv | mtenv-main/local_dm_control_suite/lqr.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Procedurally generated LQR domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import xml_tools
from lxml import etree
import numpy as np
from six.moves import range
from dm_control.utils import io as resources
_DEFAULT_TIME_LIMIT = float("inf")
_CONTROL_COST_COEF = 0.1
SUITE = containers.TaggedTasks()
def get_model_and_assets(n_bodies, n_actuators, random):
"""Returns the model description as an XML string and a dict of assets.
Args:
n_bodies: An int, number of bodies of the LQR.
n_actuators: An int, number of actuated bodies of the LQR. `n_actuators`
should be less or equal than `n_bodies`.
random: A `numpy.random.RandomState` instance.
Returns:
A tuple `(model_xml_string, assets)`, where `assets` is a dict consisting of
`{filename: contents_string}` pairs.
"""
return _make_model(n_bodies, n_actuators, random), common.ASSETS
@SUITE.add()
def lqr_2_1(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns an LQR environment with 2 bodies of which the first is actuated."""
return _make_lqr(
n_bodies=2,
n_actuators=1,
control_cost_coef=_CONTROL_COST_COEF,
time_limit=time_limit,
random=random,
environment_kwargs=environment_kwargs,
)
@SUITE.add()
def lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns an LQR environment with 6 bodies of which first 2 are actuated."""
return _make_lqr(
n_bodies=6,
n_actuators=2,
control_cost_coef=_CONTROL_COST_COEF,
time_limit=time_limit,
random=random,
environment_kwargs=environment_kwargs,
)
def _make_lqr(
n_bodies, n_actuators, control_cost_coef, time_limit, random, environment_kwargs
):
"""Returns a LQR environment.
Args:
n_bodies: An int, number of bodies of the LQR.
n_actuators: An int, number of actuated bodies of the LQR. `n_actuators`
should be less or equal than `n_bodies`.
control_cost_coef: A number, the coefficient of the control cost.
time_limit: An int, maximum time for each episode in seconds.
random: Either an existing `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically.
environment_kwargs: A `dict` specifying keyword arguments for the
environment, or None.
Returns:
A LQR environment with `n_bodies` bodies of which first `n_actuators` are
actuated.
"""
if not isinstance(random, np.random.RandomState):
random = np.random.RandomState(random)
model_string, assets = get_model_and_assets(n_bodies, n_actuators, random=random)
physics = Physics.from_xml_string(model_string, assets=assets)
task = LQRLevel(control_cost_coef, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
def _make_body(body_id, stiffness_range, damping_range, random):
"""Returns an `etree.Element` defining a body.
Args:
body_id: Id of the created body.
stiffness_range: A tuple of (stiffness_lower_bound, stiffness_uppder_bound).
The stiffness of the joint is drawn uniformly from this range.
damping_range: A tuple of (damping_lower_bound, damping_upper_bound). The
damping of the joint is drawn uniformly from this range.
random: A `numpy.random.RandomState` instance.
Returns:
A new instance of `etree.Element`. A body element with two children: joint
and geom.
"""
body_name = "body_{}".format(body_id)
joint_name = "joint_{}".format(body_id)
geom_name = "geom_{}".format(body_id)
body = etree.Element("body", name=body_name)
body.set("pos", ".25 0 0")
joint = etree.SubElement(body, "joint", name=joint_name)
body.append(etree.Element("geom", name=geom_name))
joint.set("stiffness", str(random.uniform(stiffness_range[0], stiffness_range[1])))
joint.set("damping", str(random.uniform(damping_range[0], damping_range[1])))
return body
def _make_model(
n_bodies, n_actuators, random, stiffness_range=(15, 25), damping_range=(0, 0)
):
"""Returns an MJCF XML string defining a model of springs and dampers.
Args:
n_bodies: An integer, the number of bodies (DoFs) in the system.
n_actuators: An integer, the number of actuated bodies.
random: A `numpy.random.RandomState` instance.
stiffness_range: A tuple containing minimum and maximum stiffness. Each
joint's stiffness is sampled uniformly from this interval.
damping_range: A tuple containing minimum and maximum damping. Each joint's
damping is sampled uniformly from this interval.
Returns:
An MJCF string describing the linear system.
Raises:
ValueError: If the number of bodies or actuators is erronous.
"""
if n_bodies < 1 or n_actuators < 1:
raise ValueError("At least 1 body and 1 actuator required.")
if n_actuators > n_bodies:
raise ValueError("At most 1 actuator per body.")
file_path = os.path.join(os.path.dirname(__file__), "lqr.xml")
with resources.GetResourceAsFile(file_path) as xml_file:
mjcf = xml_tools.parse(xml_file)
parent = mjcf.find("./worldbody")
actuator = etree.SubElement(mjcf.getroot(), "actuator")
tendon = etree.SubElement(mjcf.getroot(), "tendon")
for body in range(n_bodies):
# Inserting body.
child = _make_body(body, stiffness_range, damping_range, random)
site_name = "site_{}".format(body)
child.append(etree.Element("site", name=site_name))
if body == 0:
child.set("pos", ".25 0 .1")
# Add actuators to the first n_actuators bodies.
if body < n_actuators:
# Adding actuator.
joint_name = "joint_{}".format(body)
motor_name = "motor_{}".format(body)
child.find("joint").set("name", joint_name)
actuator.append(etree.Element("motor", name=motor_name, joint=joint_name))
# Add a tendon between consecutive bodies (for visualisation purposes only).
if body < n_bodies - 1:
child_site_name = "site_{}".format(body + 1)
tendon_name = "tendon_{}".format(body)
spatial = etree.SubElement(tendon, "spatial", name=tendon_name)
spatial.append(etree.Element("site", site=site_name))
spatial.append(etree.Element("site", site=child_site_name))
parent.append(child)
parent = child
return etree.tostring(mjcf, pretty_print=True)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the LQR domain."""
def state_norm(self):
"""Returns the norm of the physics state."""
return np.linalg.norm(self.state())
class LQRLevel(base.Task):
"""A Linear Quadratic Regulator `Task`."""
_TERMINAL_TOL = 1e-6
def __init__(self, control_cost_coef, random=None):
"""Initializes an LQR level with cost = sum(states^2) + c*sum(controls^2).
Args:
control_cost_coef: The coefficient of the control cost.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
Raises:
ValueError: If the control cost coefficient is not positive.
"""
if control_cost_coef <= 0:
raise ValueError("control_cost_coef must be positive.")
self._control_cost_coef = control_cost_coef
super(LQRLevel, self).__init__(random=random)
@property
def control_cost_coef(self):
return self._control_cost_coef
def initialize_episode(self, physics):
"""Random state sampled from a unit sphere."""
ndof = physics.model.nq
unit = self.random.randn(ndof)
physics.data.qpos[:] = np.sqrt(2) * unit / np.linalg.norm(unit)
super(LQRLevel, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of the state."""
obs = collections.OrderedDict()
obs["position"] = physics.position()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a quadratic state and control reward."""
position = physics.position()
state_cost = 0.5 * np.dot(position, position)
control_signal = physics.control()
control_l2_norm = 0.5 * np.dot(control_signal, control_signal)
return 1 - (state_cost + control_l2_norm * self._control_cost_coef)
def get_evaluation(self, physics):
"""Returns a sparse evaluation reward that is not used for learning."""
return float(physics.state_norm() <= 0.01)
def get_termination(self, physics):
"""Terminates when the state norm is smaller than epsilon."""
if physics.state_norm() < self._TERMINAL_TOL:
return 0.0
| 10,082 | 36.069853 | 87 | py |
mtenv | mtenv-main/local_dm_control_suite/fish.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Fish Domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
_DEFAULT_TIME_LIMIT = 40
_CONTROL_TIMESTEP = 0.04
_JOINTS = [
"tail1",
"tail_twist",
"tail2",
"finright_roll",
"finright_pitch",
"finleft_roll",
"finleft_pitch",
]
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("fish.xml"), common.ASSETS
@SUITE.add("benchmarking")
def upright(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Fish Upright task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Upright(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
@SUITE.add("benchmarking")
def swim(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Fish Swim task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Swim(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Fish domain."""
def upright(self):
"""Returns projection from z-axes of torso to the z-axes of worldbody."""
return self.named.data.xmat["torso", "zz"]
def torso_velocity(self):
"""Returns velocities and angular velocities of the torso."""
return self.data.sensordata
def joint_velocities(self):
"""Returns the joint velocities."""
return self.named.data.qvel[_JOINTS]
def joint_angles(self):
"""Returns the joint positions."""
return self.named.data.qpos[_JOINTS]
def mouth_to_target(self):
"""Returns a vector, from mouth to target in local coordinate of mouth."""
data = self.named.data
mouth_to_target_global = data.geom_xpos["target"] - data.geom_xpos["mouth"]
return mouth_to_target_global.dot(data.geom_xmat["mouth"].reshape(3, 3))
class Upright(base.Task):
"""A Fish `Task` for getting the torso upright with smooth reward."""
def __init__(self, random=None):
"""Initializes an instance of `Upright`.
Args:
random: Either an existing `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically.
"""
super(Upright, self).__init__(random=random)
def initialize_episode(self, physics):
"""Randomizes the tail and fin angles and the orientation of the Fish."""
quat = self.random.randn(4)
physics.named.data.qpos["root"][3:7] = quat / np.linalg.norm(quat)
for joint in _JOINTS:
physics.named.data.qpos[joint] = self.random.uniform(-0.2, 0.2)
# Hide the target. It's irrelevant for this task.
physics.named.model.geom_rgba["target", 3] = 0
super(Upright, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of joint angles, velocities and uprightness."""
obs = collections.OrderedDict()
obs["joint_angles"] = physics.joint_angles()
obs["upright"] = physics.upright()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a smooth reward."""
return rewards.tolerance(physics.upright(), bounds=(1, 1), margin=1)
class Swim(base.Task):
"""A Fish `Task` for swimming with smooth reward."""
def __init__(self, random=None):
"""Initializes an instance of `Swim`.
Args:
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
super(Swim, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
quat = self.random.randn(4)
physics.named.data.qpos["root"][3:7] = quat / np.linalg.norm(quat)
for joint in _JOINTS:
physics.named.data.qpos[joint] = self.random.uniform(-0.2, 0.2)
# Randomize target position.
physics.named.model.geom_pos["target", "x"] = self.random.uniform(-0.4, 0.4)
physics.named.model.geom_pos["target", "y"] = self.random.uniform(-0.4, 0.4)
physics.named.model.geom_pos["target", "z"] = self.random.uniform(0.1, 0.3)
super(Swim, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of joints, target direction and velocities."""
obs = collections.OrderedDict()
obs["joint_angles"] = physics.joint_angles()
obs["upright"] = physics.upright()
obs["target"] = physics.mouth_to_target()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a smooth reward."""
radii = physics.named.model.geom_size[["mouth", "target"], 0].sum()
in_target = rewards.tolerance(
np.linalg.norm(physics.mouth_to_target()),
bounds=(0, radii),
margin=2 * radii,
)
is_upright = 0.5 * (physics.upright() + 1)
return (7 * in_target + is_upright) / 8
| 6,657 | 34.227513 | 84 | py |
mtenv | mtenv-main/local_dm_control_suite/walker.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Planar Walker Domain."""
from __future__ import absolute_import, division, print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from dm_control.suite.utils import randomizers
from dm_control.utils import containers, rewards
from . import base, common
_DEFAULT_TIME_LIMIT = 25
_CONTROL_TIMESTEP = 0.025
# Minimal height of torso over foot above which stand reward is 1.
_STAND_HEIGHT = 1.2
# Horizontal speeds (meters/second) above which move reward is 1.
_WALK_SPEED = 1
_RUN_SPEED = 8
SUITE = containers.TaggedTasks()
def get_model_and_assets(xml_file_id):
"""Returns a tuple containing the model XML string and a dict of assets."""
if xml_file_id is not None:
filename = f"walker_{xml_file_id}.xml"
print(filename)
else:
filename = f"walker.xml"
return common.read_model(filename), common.ASSETS
@SUITE.add("benchmarking")
def stand(
time_limit=_DEFAULT_TIME_LIMIT,
xml_file_id=None,
random=None,
environment_kwargs=None,
):
"""Returns the Stand task."""
physics = Physics.from_xml_string(*get_model_and_assets(xml_file_id))
task = PlanarWalker(move_speed=0, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs,
)
@SUITE.add("benchmarking")
def walk(
time_limit=_DEFAULT_TIME_LIMIT,
xml_file_id=None,
random=None,
environment_kwargs=None,
):
"""Returns the Walk task."""
physics = Physics.from_xml_string(*get_model_and_assets(xml_file_id))
task = PlanarWalker(move_speed=_WALK_SPEED, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs,
)
@SUITE.add("benchmarking")
def run(
time_limit=_DEFAULT_TIME_LIMIT,
xml_file_id=None,
random=None,
environment_kwargs=None,
):
"""Returns the Run task."""
physics = Physics.from_xml_string(*get_model_and_assets(xml_file_id))
task = PlanarWalker(move_speed=_RUN_SPEED, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs,
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Walker domain."""
def torso_upright(self):
"""Returns projection from z-axes of torso to the z-axes of world."""
return self.named.data.xmat["torso", "zz"]
def torso_height(self):
"""Returns the height of the torso."""
return self.named.data.xpos["torso", "z"]
def horizontal_velocity(self):
"""Returns the horizontal velocity of the center-of-mass."""
return self.named.data.sensordata["torso_subtreelinvel"][0]
def orientations(self):
"""Returns planar orientations of all bodies."""
return self.named.data.xmat[1:, ["xx", "xz"]].ravel()
class PlanarWalker(base.Task):
"""A planar walker task."""
def __init__(self, move_speed, random=None):
"""Initializes an instance of `PlanarWalker`.
Args:
move_speed: A float. If this value is zero, reward is given simply for
standing up. Otherwise this specifies a target horizontal velocity for
the walking task.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._move_speed = move_speed
super(PlanarWalker, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
In 'standing' mode, use initial orientation and small velocities.
In 'random' mode, randomize joint angles and let fall to the floor.
Args:
physics: An instance of `Physics`.
"""
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
super(PlanarWalker, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of body orientations, height and velocites."""
obs = collections.OrderedDict()
obs["orientations"] = physics.orientations()
obs["height"] = physics.torso_height()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
standing = rewards.tolerance(
physics.torso_height(),
bounds=(_STAND_HEIGHT, float("inf")),
margin=_STAND_HEIGHT / 2,
)
upright = (1 + physics.torso_upright()) / 2
stand_reward = (3 * standing + upright) / 4
if self._move_speed == 0:
return stand_reward
else:
move_reward = rewards.tolerance(
physics.horizontal_velocity(),
bounds=(self._move_speed, float("inf")),
margin=self._move_speed / 2,
value_at_margin=0.5,
sigmoid="linear",
)
return stand_reward * (5 * move_reward + 1) / 6
| 6,162 | 31.267016 | 83 | py |
mtenv | mtenv-main/local_dm_control_suite/ball_in_cup.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Ball-in-Cup Domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
_DEFAULT_TIME_LIMIT = 20 # (seconds)
_CONTROL_TIMESTEP = 0.02 # (seconds)
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("ball_in_cup.xml"), common.ASSETS
@SUITE.add("benchmarking", "easy")
def catch(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Ball-in-Cup task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = BallInCup(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics with additional features for the Ball-in-Cup domain."""
def ball_to_target(self):
"""Returns the vector from the ball to the target."""
target = self.named.data.site_xpos["target", ["x", "z"]]
ball = self.named.data.xpos["ball", ["x", "z"]]
return target - ball
def in_target(self):
"""Returns 1 if the ball is in the target, 0 otherwise."""
ball_to_target = abs(self.ball_to_target())
target_size = self.named.model.site_size["target", [0, 2]]
ball_size = self.named.model.geom_size["ball", 0]
return float(all(ball_to_target < target_size - ball_size))
class BallInCup(base.Task):
"""The Ball-in-Cup task. Put the ball in the cup."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Args:
physics: An instance of `Physics`.
"""
# Find a collision-free random initial position of the ball.
penetrating = True
while penetrating:
# Assign a random ball position.
physics.named.data.qpos["ball_x"] = self.random.uniform(-0.2, 0.2)
physics.named.data.qpos["ball_z"] = self.random.uniform(0.2, 0.5)
# Check for collisions.
physics.after_reset()
penetrating = physics.data.ncon > 0
super(BallInCup, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of the state."""
obs = collections.OrderedDict()
obs["position"] = physics.position()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a sparse reward."""
return physics.in_target()
| 3,550 | 32.819048 | 80 | py |
mtenv | mtenv-main/local_dm_control_suite/finger.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Finger Domain."""
from __future__ import absolute_import, division, print_function
import collections
import numpy as np
from dm_control import mujoco
from dm_control.rl import control
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from six.moves import range
from . import base, common
_DEFAULT_TIME_LIMIT = 20 # (seconds)
_CONTROL_TIMESTEP = 0.02 # (seconds)
# For TURN tasks, the 'tip' geom needs to enter a spherical target of sizes:
_EASY_TARGET_SIZE = 0.07
_HARD_TARGET_SIZE = 0.03
# Initial spin velocity for the Stop task.
_INITIAL_SPIN_VELOCITY = 100
# Spinning slower than this value (radian/second) is considered stopped.
_STOP_VELOCITY = 1e-6
# Spinning faster than this value (radian/second) is considered spinning.
_SPIN_VELOCITY = 15.0
SUITE = containers.TaggedTasks()
def get_model_and_assets(xml_file_id):
"""Returns a tuple containing the model XML string and a dict of assets."""
if xml_file_id is not None:
filename = f"finger_{xml_file_id}.xml"
else:
filename = f"finger.xml"
return common.read_model(filename), common.ASSETS
@SUITE.add("benchmarking")
def spin(
time_limit=_DEFAULT_TIME_LIMIT,
xml_file_id=None,
random=None,
environment_kwargs=None,
):
"""Returns the Spin task."""
physics = Physics.from_xml_string(*get_model_and_assets(xml_file_id))
task = Spin(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs,
)
@SUITE.add("benchmarking")
def turn_easy(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the easy Turn task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Turn(target_radius=_EASY_TARGET_SIZE, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs,
)
@SUITE.add("benchmarking")
def turn_hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the hard Turn task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Turn(target_radius=_HARD_TARGET_SIZE, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs,
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Finger domain."""
def touch(self):
"""Returns logarithmically scaled signals from the two touch sensors."""
return np.log1p(self.named.data.sensordata[["touchtop", "touchbottom"]])
def hinge_velocity(self):
"""Returns the velocity of the hinge joint."""
return self.named.data.sensordata["hinge_velocity"]
def tip_position(self):
"""Returns the (x,z) position of the tip relative to the hinge."""
return (
self.named.data.sensordata["tip"][[0, 2]]
- self.named.data.sensordata["spinner"][[0, 2]]
)
def bounded_position(self):
"""Returns the positions, with the hinge angle replaced by tip position."""
return np.hstack(
(self.named.data.sensordata[["proximal", "distal"]], self.tip_position())
)
def velocity(self):
"""Returns the velocities (extracted from sensordata)."""
return self.named.data.sensordata[
["proximal_velocity", "distal_velocity", "hinge_velocity"]
]
def target_position(self):
"""Returns the (x,z) position of the target relative to the hinge."""
return (
self.named.data.sensordata["target"][[0, 2]]
- self.named.data.sensordata["spinner"][[0, 2]]
)
def to_target(self):
"""Returns the vector from the tip to the target."""
return self.target_position() - self.tip_position()
def dist_to_target(self):
"""Returns the signed distance to the target surface, negative is inside."""
return (
np.linalg.norm(self.to_target()) - self.named.model.site_size["target", 0]
)
class Spin(base.Task):
"""A Finger `Task` to spin the stopped body."""
def __init__(self, random=None):
"""Initializes a new `Spin` instance.
Args:
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
super(Spin, self).__init__(random=random)
def initialize_episode(self, physics):
physics.named.model.site_rgba["target", 3] = 0
physics.named.model.site_rgba["tip", 3] = 0
physics.named.model.dof_damping["hinge"] = 0.03
_set_random_joint_angles(physics, self.random)
super(Spin, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns state and touch sensors, and target info."""
obs = collections.OrderedDict()
obs["position"] = physics.bounded_position()
obs["velocity"] = physics.velocity()
obs["touch"] = physics.touch()
return obs
def get_reward(self, physics):
"""Returns a sparse reward."""
return float(physics.hinge_velocity() <= -_SPIN_VELOCITY)
class Turn(base.Task):
"""A Finger `Task` to turn the body to a target angle."""
def __init__(self, target_radius, random=None):
"""Initializes a new `Turn` instance.
Args:
target_radius: Radius of the target site, which specifies the goal angle.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._target_radius = target_radius
super(Turn, self).__init__(random=random)
def initialize_episode(self, physics):
target_angle = self.random.uniform(-np.pi, np.pi)
hinge_x, hinge_z = physics.named.data.xanchor["hinge", ["x", "z"]]
radius = physics.named.model.geom_size["cap1"].sum()
target_x = hinge_x + radius * np.sin(target_angle)
target_z = hinge_z + radius * np.cos(target_angle)
physics.named.model.site_pos["target", ["x", "z"]] = target_x, target_z
physics.named.model.site_size["target", 0] = self._target_radius
_set_random_joint_angles(physics, self.random)
super(Turn, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns state, touch sensors, and target info."""
obs = collections.OrderedDict()
obs["position"] = physics.bounded_position()
obs["velocity"] = physics.velocity()
obs["touch"] = physics.touch()
obs["target_position"] = physics.target_position()
obs["dist_to_target"] = physics.dist_to_target()
return obs
def get_reward(self, physics):
return float(physics.dist_to_target() <= 0)
def _set_random_joint_angles(physics, random, max_attempts=1000):
"""Sets the joints to a random collision-free state."""
for _ in range(max_attempts):
randomizers.randomize_limited_and_rotational_joints(physics, random)
# Check for collisions.
physics.after_reset()
if physics.data.ncon == 0:
break
else:
raise RuntimeError(
"Could not find a collision-free state "
"after {} attempts".format(max_attempts)
)
| 8,498 | 33.975309 | 86 | py |
mtenv | mtenv-main/local_dm_control_suite/point_mass.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Point-mass domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
_DEFAULT_TIME_LIMIT = 20
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("point_mass.xml"), common.ASSETS
@SUITE.add("benchmarking", "easy")
def easy(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the easy point_mass task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = PointMass(randomize_gains=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add()
def hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the hard point_mass task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = PointMass(randomize_gains=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
class Physics(mujoco.Physics):
"""physics for the point_mass domain."""
def mass_to_target(self):
"""Returns the vector from mass to target in global coordinate."""
return (
self.named.data.geom_xpos["target"] - self.named.data.geom_xpos["pointmass"]
)
def mass_to_target_dist(self):
"""Returns the distance from mass to the target."""
return np.linalg.norm(self.mass_to_target())
class PointMass(base.Task):
"""A point_mass `Task` to reach target with smooth reward."""
def __init__(self, randomize_gains, random=None):
"""Initialize an instance of `PointMass`.
Args:
randomize_gains: A `bool`, whether to randomize the actuator gains.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._randomize_gains = randomize_gains
super(PointMass, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
If _randomize_gains is True, the relationship between the controls and
the joints is randomized, so that each control actuates a random linear
combination of joints.
Args:
physics: An instance of `mujoco.Physics`.
"""
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
if self._randomize_gains:
dir1 = self.random.randn(2)
dir1 /= np.linalg.norm(dir1)
# Find another actuation direction that is not 'too parallel' to dir1.
parallel = True
while parallel:
dir2 = self.random.randn(2)
dir2 /= np.linalg.norm(dir2)
parallel = abs(np.dot(dir1, dir2)) > 0.9
physics.model.wrap_prm[[0, 1]] = dir1
physics.model.wrap_prm[[2, 3]] = dir2
super(PointMass, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of the state."""
obs = collections.OrderedDict()
obs["position"] = physics.position()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
target_size = physics.named.model.geom_size["target", 0]
near_target = rewards.tolerance(
physics.mass_to_target_dist(), bounds=(0, target_size), margin=target_size
)
control_reward = rewards.tolerance(
physics.control(), margin=1, value_at_margin=0, sigmoid="quadratic"
).mean()
small_control = (control_reward + 4) / 5
return near_target * small_control
| 5,007 | 36.096296 | 88 | py |
mtenv | mtenv-main/local_dm_control_suite/quadruped.py | # Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Quadruped Domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.mujoco.wrapper import mjbindings
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import rewards
from dm_control.utils import xml_tools
from lxml import etree
import numpy as np
from scipy import ndimage
enums = mjbindings.enums
mjlib = mjbindings.mjlib
_DEFAULT_TIME_LIMIT = 20
_CONTROL_TIMESTEP = 0.02
# Horizontal speeds above which the move reward is 1.
_RUN_SPEED = 5
_WALK_SPEED = 0.5
# Constants related to terrain generation.
_HEIGHTFIELD_ID = 0
_TERRAIN_SMOOTHNESS = 0.15 # 0.0: maximally bumpy; 1.0: completely smooth.
_TERRAIN_BUMP_SCALE = 2 # Spatial scale of terrain bumps (in meters).
# Named model elements.
_TOES = ["toe_front_left", "toe_back_left", "toe_back_right", "toe_front_right"]
_WALLS = ["wall_px", "wall_py", "wall_nx", "wall_ny"]
SUITE = containers.TaggedTasks()
def make_model(
floor_size=None, terrain=False, rangefinders=False, walls_and_ball=False
):
"""Returns the model XML string."""
xml_string = common.read_model("quadruped.xml")
parser = etree.XMLParser(remove_blank_text=True)
mjcf = etree.XML(xml_string, parser)
# Set floor size.
if floor_size is not None:
floor_geom = mjcf.find(".//geom[@name={!r}]".format("floor"))
floor_geom.attrib["size"] = "{} {} .5".format(floor_size, floor_size)
# Remove walls, ball and target.
if not walls_and_ball:
for wall in _WALLS:
wall_geom = xml_tools.find_element(mjcf, "geom", wall)
wall_geom.getparent().remove(wall_geom)
# Remove ball.
ball_body = xml_tools.find_element(mjcf, "body", "ball")
ball_body.getparent().remove(ball_body)
# Remove target.
target_site = xml_tools.find_element(mjcf, "site", "target")
target_site.getparent().remove(target_site)
# Remove terrain.
if not terrain:
terrain_geom = xml_tools.find_element(mjcf, "geom", "terrain")
terrain_geom.getparent().remove(terrain_geom)
# Remove rangefinders if they're not used, as range computations can be
# expensive, especially in a scene with heightfields.
if not rangefinders:
rangefinder_sensors = mjcf.findall(".//rangefinder")
for rf in rangefinder_sensors:
rf.getparent().remove(rf)
return etree.tostring(mjcf, pretty_print=True)
@SUITE.add()
def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Walk task."""
xml_string = make_model(floor_size=_DEFAULT_TIME_LIMIT * _WALK_SPEED)
physics = Physics.from_xml_string(xml_string, common.ASSETS)
task = Move(desired_speed=_WALK_SPEED, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add()
def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Run task."""
xml_string = make_model(floor_size=_DEFAULT_TIME_LIMIT * _RUN_SPEED)
physics = Physics.from_xml_string(xml_string, common.ASSETS)
task = Move(desired_speed=_RUN_SPEED, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add()
def escape(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Escape task."""
xml_string = make_model(floor_size=40, terrain=True, rangefinders=True)
physics = Physics.from_xml_string(xml_string, common.ASSETS)
task = Escape(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add()
def fetch(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Fetch task."""
xml_string = make_model(walls_and_ball=True)
physics = Physics.from_xml_string(xml_string, common.ASSETS)
task = Fetch(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Quadruped domain."""
def _reload_from_data(self, data):
super(Physics, self)._reload_from_data(data)
# Clear cached sensor names when the physics is reloaded.
self._sensor_types_to_names = {}
self._hinge_names = []
def _get_sensor_names(self, *sensor_types):
try:
sensor_names = self._sensor_types_to_names[sensor_types]
except KeyError:
[sensor_ids] = np.where(np.in1d(self.model.sensor_type, sensor_types))
sensor_names = [self.model.id2name(s_id, "sensor") for s_id in sensor_ids]
self._sensor_types_to_names[sensor_types] = sensor_names
return sensor_names
def torso_upright(self):
"""Returns the dot-product of the torso z-axis and the global z-axis."""
return np.asarray(self.named.data.xmat["torso", "zz"])
def torso_velocity(self):
"""Returns the velocity of the torso, in the local frame."""
return self.named.data.sensordata["velocimeter"].copy()
def egocentric_state(self):
"""Returns the state without global orientation or position."""
if not self._hinge_names:
[hinge_ids] = np.nonzero(self.model.jnt_type == enums.mjtJoint.mjJNT_HINGE)
self._hinge_names = [
self.model.id2name(j_id, "joint") for j_id in hinge_ids
]
return np.hstack(
(
self.named.data.qpos[self._hinge_names],
self.named.data.qvel[self._hinge_names],
self.data.act,
)
)
def toe_positions(self):
"""Returns toe positions in egocentric frame."""
torso_frame = self.named.data.xmat["torso"].reshape(3, 3)
torso_pos = self.named.data.xpos["torso"]
torso_to_toe = self.named.data.xpos[_TOES] - torso_pos
return torso_to_toe.dot(torso_frame)
def force_torque(self):
"""Returns scaled force/torque sensor readings at the toes."""
force_torque_sensors = self._get_sensor_names(
enums.mjtSensor.mjSENS_FORCE, enums.mjtSensor.mjSENS_TORQUE
)
return np.arcsinh(self.named.data.sensordata[force_torque_sensors])
def imu(self):
"""Returns IMU-like sensor readings."""
imu_sensors = self._get_sensor_names(
enums.mjtSensor.mjSENS_GYRO, enums.mjtSensor.mjSENS_ACCELEROMETER
)
return self.named.data.sensordata[imu_sensors]
def rangefinder(self):
"""Returns scaled rangefinder sensor readings."""
rf_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_RANGEFINDER)
rf_readings = self.named.data.sensordata[rf_sensors]
no_intersection = -1.0
return np.where(rf_readings == no_intersection, 1.0, np.tanh(rf_readings))
def origin_distance(self):
"""Returns the distance from the origin to the workspace."""
return np.asarray(np.linalg.norm(self.named.data.site_xpos["workspace"]))
def origin(self):
"""Returns origin position in the torso frame."""
torso_frame = self.named.data.xmat["torso"].reshape(3, 3)
torso_pos = self.named.data.xpos["torso"]
return -torso_pos.dot(torso_frame)
def ball_state(self):
"""Returns ball position and velocity relative to the torso frame."""
data = self.named.data
torso_frame = data.xmat["torso"].reshape(3, 3)
ball_rel_pos = data.xpos["ball"] - data.xpos["torso"]
ball_rel_vel = data.qvel["ball_root"][:3] - data.qvel["root"][:3]
ball_rot_vel = data.qvel["ball_root"][3:]
ball_state = np.vstack((ball_rel_pos, ball_rel_vel, ball_rot_vel))
return ball_state.dot(torso_frame).ravel()
def target_position(self):
"""Returns target position in torso frame."""
torso_frame = self.named.data.xmat["torso"].reshape(3, 3)
torso_pos = self.named.data.xpos["torso"]
torso_to_target = self.named.data.site_xpos["target"] - torso_pos
return torso_to_target.dot(torso_frame)
def ball_to_target_distance(self):
"""Returns horizontal distance from the ball to the target."""
ball_to_target = (
self.named.data.site_xpos["target"] - self.named.data.xpos["ball"]
)
return np.linalg.norm(ball_to_target[:2])
def self_to_ball_distance(self):
"""Returns horizontal distance from the quadruped workspace to the ball."""
self_to_ball = (
self.named.data.site_xpos["workspace"] - self.named.data.xpos["ball"]
)
return np.linalg.norm(self_to_ball[:2])
def _find_non_contacting_height(physics, orientation, x_pos=0.0, y_pos=0.0):
"""Find a height with no contacts given a body orientation.
Args:
physics: An instance of `Physics`.
orientation: A quaternion.
x_pos: A float. Position along global x-axis.
y_pos: A float. Position along global y-axis.
Raises:
RuntimeError: If a non-contacting configuration has not been found after
10,000 attempts.
"""
z_pos = 0.0 # Start embedded in the floor.
num_contacts = 1
num_attempts = 0
# Move up in 1cm increments until no contacts.
while num_contacts > 0:
try:
with physics.reset_context():
physics.named.data.qpos["root"][:3] = x_pos, y_pos, z_pos
physics.named.data.qpos["root"][3:] = orientation
except control.PhysicsError:
# We may encounter a PhysicsError here due to filling the contact
# buffer, in which case we simply increment the height and continue.
pass
num_contacts = physics.data.ncon
z_pos += 0.01
num_attempts += 1
if num_attempts > 10000:
raise RuntimeError("Failed to find a non-contacting configuration.")
def _common_observations(physics):
"""Returns the observations common to all tasks."""
obs = collections.OrderedDict()
obs["egocentric_state"] = physics.egocentric_state()
obs["torso_velocity"] = physics.torso_velocity()
obs["torso_upright"] = physics.torso_upright()
obs["imu"] = physics.imu()
obs["force_torque"] = physics.force_torque()
return obs
def _upright_reward(physics, deviation_angle=0):
"""Returns a reward proportional to how upright the torso is.
Args:
physics: an instance of `Physics`.
deviation_angle: A float, in degrees. The reward is 0 when the torso is
exactly upside-down and 1 when the torso's z-axis is less than
`deviation_angle` away from the global z-axis.
"""
deviation = np.cos(np.deg2rad(deviation_angle))
return rewards.tolerance(
physics.torso_upright(),
bounds=(deviation, float("inf")),
sigmoid="linear",
margin=1 + deviation,
value_at_margin=0,
)
class Move(base.Task):
"""A quadruped task solved by moving forward at a designated speed."""
def __init__(self, desired_speed, random=None):
"""Initializes an instance of `Move`.
Args:
desired_speed: A float. If this value is zero, reward is given simply
for standing upright. Otherwise this specifies the horizontal velocity
at which the velocity-dependent reward component is maximized.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._desired_speed = desired_speed
super(Move, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Args:
physics: An instance of `Physics`.
"""
# Initial configuration.
orientation = self.random.randn(4)
orientation /= np.linalg.norm(orientation)
_find_non_contacting_height(physics, orientation)
super(Move, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation to the agent."""
return _common_observations(physics)
def get_reward(self, physics):
"""Returns a reward to the agent."""
# Move reward term.
move_reward = rewards.tolerance(
physics.torso_velocity()[0],
bounds=(self._desired_speed, float("inf")),
margin=self._desired_speed,
value_at_margin=0.5,
sigmoid="linear",
)
return _upright_reward(physics) * move_reward
class Escape(base.Task):
"""A quadruped task solved by escaping a bowl-shaped terrain."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Args:
physics: An instance of `Physics`.
"""
# Get heightfield resolution, assert that it is square.
res = physics.model.hfield_nrow[_HEIGHTFIELD_ID]
assert res == physics.model.hfield_ncol[_HEIGHTFIELD_ID]
# Sinusoidal bowl shape.
row_grid, col_grid = np.ogrid[-1 : 1 : res * 1j, -1 : 1 : res * 1j]
radius = np.clip(np.sqrt(col_grid ** 2 + row_grid ** 2), 0.04, 1)
bowl_shape = 0.5 - np.cos(2 * np.pi * radius) / 2
# Random smooth bumps.
terrain_size = 2 * physics.model.hfield_size[_HEIGHTFIELD_ID, 0]
bump_res = int(terrain_size / _TERRAIN_BUMP_SCALE)
bumps = self.random.uniform(_TERRAIN_SMOOTHNESS, 1, (bump_res, bump_res))
smooth_bumps = ndimage.zoom(bumps, res / float(bump_res))
# Terrain is elementwise product.
terrain = bowl_shape * smooth_bumps
start_idx = physics.model.hfield_adr[_HEIGHTFIELD_ID]
physics.model.hfield_data[start_idx : start_idx + res ** 2] = terrain.ravel()
super(Escape, self).initialize_episode(physics)
# If we have a rendering context, we need to re-upload the modified
# heightfield data.
if physics.contexts:
with physics.contexts.gl.make_current() as ctx:
ctx.call(
mjlib.mjr_uploadHField,
physics.model.ptr,
physics.contexts.mujoco.ptr,
_HEIGHTFIELD_ID,
)
# Initial configuration.
orientation = self.random.randn(4)
orientation /= np.linalg.norm(orientation)
_find_non_contacting_height(physics, orientation)
def get_observation(self, physics):
"""Returns an observation to the agent."""
obs = _common_observations(physics)
obs["origin"] = physics.origin()
obs["rangefinder"] = physics.rangefinder()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
# Escape reward term.
terrain_size = physics.model.hfield_size[_HEIGHTFIELD_ID, 0]
escape_reward = rewards.tolerance(
physics.origin_distance(),
bounds=(terrain_size, float("inf")),
margin=terrain_size,
value_at_margin=0,
sigmoid="linear",
)
return _upright_reward(physics, deviation_angle=20) * escape_reward
class Fetch(base.Task):
"""A quadruped task solved by bringing a ball to the origin."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Args:
physics: An instance of `Physics`.
"""
# Initial configuration, random azimuth and horizontal position.
azimuth = self.random.uniform(0, 2 * np.pi)
orientation = np.array((np.cos(azimuth / 2), 0, 0, np.sin(azimuth / 2)))
spawn_radius = 0.9 * physics.named.model.geom_size["floor", 0]
x_pos, y_pos = self.random.uniform(-spawn_radius, spawn_radius, size=(2,))
_find_non_contacting_height(physics, orientation, x_pos, y_pos)
# Initial ball state.
physics.named.data.qpos["ball_root"][:2] = self.random.uniform(
-spawn_radius, spawn_radius, size=(2,)
)
physics.named.data.qpos["ball_root"][2] = 2
physics.named.data.qvel["ball_root"][:2] = 5 * self.random.randn(2)
super(Fetch, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation to the agent."""
obs = _common_observations(physics)
obs["ball_state"] = physics.ball_state()
obs["target_position"] = physics.target_position()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
# Reward for moving close to the ball.
arena_radius = physics.named.model.geom_size["floor", 0] * np.sqrt(2)
workspace_radius = physics.named.model.site_size["workspace", 0]
ball_radius = physics.named.model.geom_size["ball", 0]
reach_reward = rewards.tolerance(
physics.self_to_ball_distance(),
bounds=(0, workspace_radius + ball_radius),
sigmoid="linear",
margin=arena_radius,
value_at_margin=0,
)
# Reward for bringing the ball to the target.
target_radius = physics.named.model.site_size["target", 0]
fetch_reward = rewards.tolerance(
physics.ball_to_target_distance(),
bounds=(0, target_radius),
sigmoid="linear",
margin=arena_radius,
value_at_margin=0,
)
reach_then_fetch = reach_reward * (0.5 + 0.5 * fetch_reward)
return _upright_reward(physics) * reach_then_fetch
| 19,110 | 36.108738 | 87 | py |
mtenv | mtenv-main/local_dm_control_suite/swimmer.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Procedurally generated Swimmer domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from dm_control.utils import rewards
from lxml import etree
import numpy as np
from six.moves import range
_DEFAULT_TIME_LIMIT = 30
_CONTROL_TIMESTEP = 0.03 # (Seconds)
SUITE = containers.TaggedTasks()
def get_model_and_assets(n_joints):
"""Returns a tuple containing the model XML string and a dict of assets.
Args:
n_joints: An integer specifying the number of joints in the swimmer.
Returns:
A tuple `(model_xml_string, assets)`, where `assets` is a dict consisting of
`{filename: contents_string}` pairs.
"""
return _make_model(n_joints), common.ASSETS
@SUITE.add("benchmarking")
def swimmer6(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns a 6-link swimmer."""
return _make_swimmer(
6, time_limit, random=random, environment_kwargs=environment_kwargs
)
@SUITE.add("benchmarking")
def swimmer15(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns a 15-link swimmer."""
return _make_swimmer(
15, time_limit, random=random, environment_kwargs=environment_kwargs
)
def swimmer(
n_links=3, time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns a swimmer with n links."""
return _make_swimmer(
n_links, time_limit, random=random, environment_kwargs=environment_kwargs
)
def _make_swimmer(
n_joints, time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns a swimmer control environment."""
model_string, assets = get_model_and_assets(n_joints)
physics = Physics.from_xml_string(model_string, assets=assets)
task = Swimmer(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
def _make_model(n_bodies):
"""Generates an xml string defining a swimmer with `n_bodies` bodies."""
if n_bodies < 3:
raise ValueError("At least 3 bodies required. Received {}".format(n_bodies))
mjcf = etree.fromstring(common.read_model("swimmer.xml"))
head_body = mjcf.find("./worldbody/body")
actuator = etree.SubElement(mjcf, "actuator")
sensor = etree.SubElement(mjcf, "sensor")
parent = head_body
for body_index in range(n_bodies - 1):
site_name = "site_{}".format(body_index)
child = _make_body(body_index=body_index)
child.append(etree.Element("site", name=site_name))
joint_name = "joint_{}".format(body_index)
joint_limit = 360.0 / n_bodies
joint_range = "{} {}".format(-joint_limit, joint_limit)
child.append(etree.Element("joint", {"name": joint_name, "range": joint_range}))
motor_name = "motor_{}".format(body_index)
actuator.append(etree.Element("motor", name=motor_name, joint=joint_name))
velocimeter_name = "velocimeter_{}".format(body_index)
sensor.append(
etree.Element("velocimeter", name=velocimeter_name, site=site_name)
)
gyro_name = "gyro_{}".format(body_index)
sensor.append(etree.Element("gyro", name=gyro_name, site=site_name))
parent.append(child)
parent = child
# Move tracking cameras further away from the swimmer according to its length.
cameras = mjcf.findall("./worldbody/body/camera")
scale = n_bodies / 6.0
for cam in cameras:
if cam.get("mode") == "trackcom":
old_pos = cam.get("pos").split(" ")
new_pos = " ".join([str(float(dim) * scale) for dim in old_pos])
cam.set("pos", new_pos)
return etree.tostring(mjcf, pretty_print=True)
def _make_body(body_index):
"""Generates an xml string defining a single physical body."""
body_name = "segment_{}".format(body_index)
visual_name = "visual_{}".format(body_index)
inertial_name = "inertial_{}".format(body_index)
body = etree.Element("body", name=body_name)
body.set("pos", "0 .1 0")
etree.SubElement(body, "geom", {"class": "visual", "name": visual_name})
etree.SubElement(body, "geom", {"class": "inertial", "name": inertial_name})
return body
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the swimmer domain."""
def nose_to_target(self):
"""Returns a vector from nose to target in local coordinate of the head."""
nose_to_target = (
self.named.data.geom_xpos["target"] - self.named.data.geom_xpos["nose"]
)
head_orientation = self.named.data.xmat["head"].reshape(3, 3)
return nose_to_target.dot(head_orientation)[:2]
def nose_to_target_dist(self):
"""Returns the distance from the nose to the target."""
return np.linalg.norm(self.nose_to_target())
def body_velocities(self):
"""Returns local body velocities: x,y linear, z rotational."""
xvel_local = self.data.sensordata[12:].reshape((-1, 6))
vx_vy_wz = [0, 1, 5] # Indices for linear x,y vels and rotational z vel.
return xvel_local[:, vx_vy_wz].ravel()
def joints(self):
"""Returns all internal joint angles (excluding root joints)."""
return self.data.qpos[3:].copy()
class Swimmer(base.Task):
"""A swimmer `Task` to reach the target or just swim."""
def __init__(self, random=None):
"""Initializes an instance of `Swimmer`.
Args:
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
super(Swimmer, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Initializes the swimmer orientation to [-pi, pi) and the relative joint
angle of each joint uniformly within its range.
Args:
physics: An instance of `Physics`.
"""
# Random joint angles:
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
# Random target position.
close_target = self.random.rand() < 0.2 # Probability of a close target.
target_box = 0.3 if close_target else 2
xpos, ypos = self.random.uniform(-target_box, target_box, size=2)
physics.named.model.geom_pos["target", "x"] = xpos
physics.named.model.geom_pos["target", "y"] = ypos
physics.named.model.light_pos["target_light", "x"] = xpos
physics.named.model.light_pos["target_light", "y"] = ypos
super(Swimmer, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of joint angles, body velocities and target."""
obs = collections.OrderedDict()
obs["joints"] = physics.joints()
obs["to_target"] = physics.nose_to_target()
obs["body_velocities"] = physics.body_velocities()
return obs
def get_reward(self, physics):
"""Returns a smooth reward."""
target_size = physics.named.model.geom_size["target", 0]
return rewards.tolerance(
physics.nose_to_target_dist(),
bounds=(0, target_size),
margin=5 * target_size,
sigmoid="long_tail",
)
| 8,432 | 36.314159 | 88 | py |
mtenv | mtenv-main/local_dm_control_suite/reacher.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Reacher domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
SUITE = containers.TaggedTasks()
_DEFAULT_TIME_LIMIT = 20
_BIG_TARGET = 0.05
_SMALL_TARGET = 0.015
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("reacher.xml"), common.ASSETS
@SUITE.add("benchmarking", "easy")
def easy(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns reacher with sparse reward with 5e-2 tol and randomized target."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Reacher(target_size=_BIG_TARGET, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add("benchmarking")
def hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns reacher with sparse reward with 1e-2 tol and randomized target."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Reacher(target_size=_SMALL_TARGET, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Reacher domain."""
def finger_to_target(self):
"""Returns the vector from target to finger in global coordinates."""
return (
self.named.data.geom_xpos["target", :2]
- self.named.data.geom_xpos["finger", :2]
)
def finger_to_target_dist(self):
"""Returns the signed distance between the finger and target surface."""
return np.linalg.norm(self.finger_to_target())
class Reacher(base.Task):
"""A reacher `Task` to reach the target."""
def __init__(self, target_size, random=None):
"""Initialize an instance of `Reacher`.
Args:
target_size: A `float`, tolerance to determine whether finger reached the
target.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._target_size = target_size
super(Reacher, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
physics.named.model.geom_size["target", 0] = self._target_size
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
# Randomize target position
angle = self.random.uniform(0, 2 * np.pi)
radius = self.random.uniform(0.05, 0.20)
physics.named.model.geom_pos["target", "x"] = radius * np.sin(angle)
physics.named.model.geom_pos["target", "y"] = radius * np.cos(angle)
super(Reacher, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of the state and the target position."""
obs = collections.OrderedDict()
obs["position"] = physics.position()
obs["to_target"] = physics.finger_to_target()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
radii = physics.named.model.geom_size[["target", "finger"], 0].sum()
return rewards.tolerance(physics.finger_to_target_dist(), (0, radii))
| 4,543 | 36.553719 | 83 | py |
mtenv | mtenv-main/local_dm_control_suite/pendulum.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Pendulum domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
_DEFAULT_TIME_LIMIT = 20
_ANGLE_BOUND = 8
_COSINE_BOUND = np.cos(np.deg2rad(_ANGLE_BOUND))
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("pendulum.xml"), common.ASSETS
@SUITE.add("benchmarking")
def swingup(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns pendulum swingup task ."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = SwingUp(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Pendulum domain."""
def pole_vertical(self):
"""Returns vertical (z) component of pole frame."""
return self.named.data.xmat["pole", "zz"]
def angular_velocity(self):
"""Returns the angular velocity of the pole."""
return self.named.data.qvel["hinge"].copy()
def pole_orientation(self):
"""Returns both horizontal and vertical components of pole frame."""
return self.named.data.xmat["pole", ["zz", "xz"]]
class SwingUp(base.Task):
"""A Pendulum `Task` to swing up and balance the pole."""
def __init__(self, random=None):
"""Initialize an instance of `Pendulum`.
Args:
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
super(SwingUp, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Pole is set to a random angle between [-pi, pi).
Args:
physics: An instance of `Physics`.
"""
physics.named.data.qpos["hinge"] = self.random.uniform(-np.pi, np.pi)
super(SwingUp, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation.
Observations are states concatenating pole orientation and angular velocity
and pixels from fixed camera.
Args:
physics: An instance of `physics`, Pendulum physics.
Returns:
A `dict` of observation.
"""
obs = collections.OrderedDict()
obs["orientation"] = physics.pole_orientation()
obs["velocity"] = physics.angular_velocity()
return obs
def get_reward(self, physics):
return rewards.tolerance(physics.pole_vertical(), (_COSINE_BOUND, 1))
| 3,748 | 31.6 | 83 | py |
mtenv | mtenv-main/local_dm_control_suite/lqr_solver.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
r"""Optimal policy for LQR levels.
LQR control problem is described in
https://en.wikipedia.org/wiki/Linear-quadratic_regulator#Infinite-horizon.2C_discrete-time_LQR
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
from dm_control.mujoco import wrapper
import numpy as np
from six.moves import range
try:
import scipy.linalg as sp # pylint: disable=g-import-not-at-top
except ImportError:
sp = None
def _solve_dare(a, b, q, r):
"""Solves the Discrete-time Algebraic Riccati Equation (DARE) by iteration.
Algebraic Riccati Equation:
```none
P_{t-1} = Q + A' * P_{t} * A -
A' * P_{t} * B * (R + B' * P_{t} * B)^{-1} * B' * P_{t} * A
```
Args:
a: A 2 dimensional numpy array, transition matrix A.
b: A 2 dimensional numpy array, control matrix B.
q: A 2 dimensional numpy array, symmetric positive definite cost matrix.
r: A 2 dimensional numpy array, symmetric positive definite cost matrix
Returns:
A numpy array, a real symmetric matrix P which is the solution to DARE.
Raises:
RuntimeError: If the computed P matrix is not symmetric and
positive-definite.
"""
p = np.eye(len(a))
for _ in range(1000000):
a_p = a.T.dot(p) # A' * P_t
a_p_b = np.dot(a_p, b) # A' * P_t * B
# Algebraic Riccati Equation.
p_next = (
q
+ np.dot(a_p, a)
- a_p_b.dot(np.linalg.solve(b.T.dot(p.dot(b)) + r, a_p_b.T))
)
p_next += p_next.T
p_next *= 0.5
if np.abs(p - p_next).max() < 1e-12:
break
p = p_next
else:
logging.warning("DARE solver did not converge")
try:
# Check that the result is symmetric and positive-definite.
np.linalg.cholesky(p_next)
except np.linalg.LinAlgError:
raise RuntimeError(
"ARE solver failed: P matrix is not symmetric and " "positive-definite."
)
return p_next
def solve(env):
"""Returns the optimal value and policy for LQR problem.
Args:
env: An instance of `control.EnvironmentV2` with LQR level.
Returns:
p: A numpy array, the Hessian of the optimal total cost-to-go (value
function at state x) is V(x) = .5 * x' * p * x.
k: A numpy array which gives the optimal linear policy u = k * x.
beta: The maximum eigenvalue of (a + b * k). Under optimal policy, at
timestep n the state tends to 0 like beta^n.
Raises:
RuntimeError: If the controlled system is unstable.
"""
n = env.physics.model.nq # number of DoFs
m = env.physics.model.nu # number of controls
# Compute the mass matrix.
mass = np.zeros((n, n))
wrapper.mjbindings.mjlib.mj_fullM(env.physics.model.ptr, mass, env.physics.data.qM)
# Compute input matrices a, b, q and r to the DARE solvers.
# State transition matrix a.
stiffness = np.diag(env.physics.model.jnt_stiffness.ravel())
damping = np.diag(env.physics.model.dof_damping.ravel())
dt = env.physics.model.opt.timestep
j = np.linalg.solve(-mass, np.hstack((stiffness, damping)))
a = np.eye(2 * n) + dt * np.vstack(
(dt * j + np.hstack((np.zeros((n, n)), np.eye(n))), j)
)
# Control transition matrix b.
b = env.physics.data.actuator_moment.T
bc = np.linalg.solve(mass, b)
b = dt * np.vstack((dt * bc, bc))
# State cost Hessian q.
q = np.diag(np.hstack([np.ones(n), np.zeros(n)]))
# Control cost Hessian r.
r = env.task.control_cost_coef * np.eye(m)
if sp:
# Use scipy's faster DARE solver if available.
solve_dare = sp.solve_discrete_are
else:
# Otherwise fall back on a slower internal implementation.
solve_dare = _solve_dare
# Solve the discrete algebraic Riccati equation.
p = solve_dare(a, b, q, r)
k = -np.linalg.solve(b.T.dot(p.dot(b)) + r, b.T.dot(p.dot(a)))
# Under optimal policy, state tends to 0 like beta^n_timesteps
beta = np.abs(np.linalg.eigvals(a + b.dot(k))).max()
if beta >= 1.0:
raise RuntimeError("Controlled system is unstable.")
return p, k, beta
| 4,910 | 32.408163 | 94 | py |
mtenv | mtenv-main/local_dm_control_suite/stacker.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Planar Stacker domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import rewards
from dm_control.utils import xml_tools
from lxml import etree
import numpy as np
_CLOSE = 0.01 # (Meters) Distance below which a thing is considered close.
_CONTROL_TIMESTEP = 0.01 # (Seconds)
_TIME_LIMIT = 10 # (Seconds)
_ARM_JOINTS = [
"arm_root",
"arm_shoulder",
"arm_elbow",
"arm_wrist",
"finger",
"fingertip",
"thumb",
"thumbtip",
]
SUITE = containers.TaggedTasks()
def make_model(n_boxes):
"""Returns a tuple containing the model XML string and a dict of assets."""
xml_string = common.read_model("stacker.xml")
parser = etree.XMLParser(remove_blank_text=True)
mjcf = etree.XML(xml_string, parser)
# Remove unused boxes
for b in range(n_boxes, 4):
box = xml_tools.find_element(mjcf, "body", "box" + str(b))
box.getparent().remove(box)
return etree.tostring(mjcf, pretty_print=True), common.ASSETS
@SUITE.add("hard")
def stack_2(
fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns stacker task with 2 boxes."""
n_boxes = 2
physics = Physics.from_xml_string(*make_model(n_boxes=n_boxes))
task = Stack(n_boxes=n_boxes, fully_observable=fully_observable, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
@SUITE.add("hard")
def stack_4(
fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns stacker task with 4 boxes."""
n_boxes = 4
physics = Physics.from_xml_string(*make_model(n_boxes=n_boxes))
task = Stack(n_boxes=n_boxes, fully_observable=fully_observable, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics with additional features for the Planar Manipulator domain."""
def bounded_joint_pos(self, joint_names):
"""Returns joint positions as (sin, cos) values."""
joint_pos = self.named.data.qpos[joint_names]
return np.vstack([np.sin(joint_pos), np.cos(joint_pos)]).T
def joint_vel(self, joint_names):
"""Returns joint velocities."""
return self.named.data.qvel[joint_names]
def body_2d_pose(self, body_names, orientation=True):
"""Returns positions and/or orientations of bodies."""
if not isinstance(body_names, str):
body_names = np.array(body_names).reshape(-1, 1) # Broadcast indices.
pos = self.named.data.xpos[body_names, ["x", "z"]]
if orientation:
ori = self.named.data.xquat[body_names, ["qw", "qy"]]
return np.hstack([pos, ori])
else:
return pos
def touch(self):
return np.log1p(self.data.sensordata)
def site_distance(self, site1, site2):
site1_to_site2 = np.diff(self.named.data.site_xpos[[site2, site1]], axis=0)
return np.linalg.norm(site1_to_site2)
class Stack(base.Task):
"""A Stack `Task`: stack the boxes."""
def __init__(self, n_boxes, fully_observable, random=None):
"""Initialize an instance of the `Stack` task.
Args:
n_boxes: An `int`, number of boxes to stack.
fully_observable: A `bool`, whether the observation should contain the
positions and velocities of the boxes and the location of the target.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._n_boxes = n_boxes
self._box_names = ["box" + str(b) for b in range(n_boxes)]
self._box_joint_names = []
for name in self._box_names:
for dim in "xyz":
self._box_joint_names.append("_".join([name, dim]))
self._fully_observable = fully_observable
super(Stack, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
# Local aliases
randint = self.random.randint
uniform = self.random.uniform
model = physics.named.model
data = physics.named.data
# Find a collision-free random initial configuration.
penetrating = True
while penetrating:
# Randomise angles of arm joints.
is_limited = model.jnt_limited[_ARM_JOINTS].astype(np.bool)
joint_range = model.jnt_range[_ARM_JOINTS]
lower_limits = np.where(is_limited, joint_range[:, 0], -np.pi)
upper_limits = np.where(is_limited, joint_range[:, 1], np.pi)
angles = uniform(lower_limits, upper_limits)
data.qpos[_ARM_JOINTS] = angles
# Symmetrize hand.
data.qpos["finger"] = data.qpos["thumb"]
# Randomise target location.
target_height = 2 * randint(self._n_boxes) + 1
box_size = model.geom_size["target", 0]
model.body_pos["target", "z"] = box_size * target_height
model.body_pos["target", "x"] = uniform(-0.37, 0.37)
# Randomise box locations.
for name in self._box_names:
data.qpos[name + "_x"] = uniform(0.1, 0.3)
data.qpos[name + "_z"] = uniform(0, 0.7)
data.qpos[name + "_y"] = uniform(0, 2 * np.pi)
# Check for collisions.
physics.after_reset()
penetrating = physics.data.ncon > 0
super(Stack, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns either features or only sensors (to be used with pixels)."""
obs = collections.OrderedDict()
obs["arm_pos"] = physics.bounded_joint_pos(_ARM_JOINTS)
obs["arm_vel"] = physics.joint_vel(_ARM_JOINTS)
obs["touch"] = physics.touch()
if self._fully_observable:
obs["hand_pos"] = physics.body_2d_pose("hand")
obs["box_pos"] = physics.body_2d_pose(self._box_names)
obs["box_vel"] = physics.joint_vel(self._box_joint_names)
obs["target_pos"] = physics.body_2d_pose("target", orientation=False)
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
box_size = physics.named.model.geom_size["target", 0]
min_box_to_target_distance = min(
physics.site_distance(name, "target") for name in self._box_names
)
box_is_close = rewards.tolerance(
min_box_to_target_distance, margin=2 * box_size
)
hand_to_target_distance = physics.site_distance("grasp", "target")
hand_is_far = rewards.tolerance(
hand_to_target_distance, bounds=(0.1, float("inf")), margin=_CLOSE
)
return box_is_close * hand_is_far
| 8,131 | 35.142222 | 87 | py |
mtenv | mtenv-main/local_dm_control_suite/cheetah.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Cheetah Domain."""
from __future__ import absolute_import, division, print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from dm_control.utils import containers, rewards
from . import base, common
# How long the simulation will run, in seconds.
_DEFAULT_TIME_LIMIT = 10
# Running speed above which reward is 1.
_RUN_SPEED = 10
SUITE = containers.TaggedTasks()
def get_model_and_assets(xml_file_id):
"""Returns a tuple containing the model XML string and a dict of assets."""
if xml_file_id is not None:
filename = f"cheetah_{xml_file_id}.xml"
print(filename)
else:
filename = f"cheetah.xml"
return common.read_model(filename), common.ASSETS
@SUITE.add("benchmarking")
def run(
time_limit=_DEFAULT_TIME_LIMIT,
xml_file_id=None,
random=None,
environment_kwargs=None,
):
"""Returns the run task."""
physics = Physics.from_xml_string(*get_model_and_assets(xml_file_id))
task = Cheetah(random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Cheetah domain."""
def speed(self):
"""Returns the horizontal speed of the Cheetah."""
return self.named.data.sensordata["torso_subtreelinvel"][0]
class Cheetah(base.Task):
"""A `Task` to train a running Cheetah."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
# The indexing below assumes that all joints have a single DOF.
assert physics.model.nq == physics.model.njnt
is_limited = physics.model.jnt_limited == 1
lower, upper = physics.model.jnt_range[is_limited].T
physics.data.qpos[is_limited] = self.random.uniform(lower, upper)
# Stabilize the model before the actual simulation.
for _ in range(200):
physics.step()
physics.data.time = 0
self._timeout_progress = 0
super(Cheetah, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of the state, ignoring horizontal position."""
obs = collections.OrderedDict()
# Ignores horizontal position to maintain translational invariance.
obs["position"] = physics.data.qpos[1:].copy()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
return rewards.tolerance(
physics.speed(),
bounds=(_RUN_SPEED, float("inf")),
margin=_RUN_SPEED,
value_at_margin=0,
sigmoid="linear",
)
| 3,505 | 32.075472 | 80 | py |
mtenv | mtenv-main/local_dm_control_suite/__init__.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A collection of MuJoCo-based Reinforcement Learning environments."""
from __future__ import absolute_import, division, print_function
import collections
import inspect
import itertools
import sys
from dm_control.rl import control
from . import (
acrobot,
ball_in_cup,
cartpole,
cheetah,
finger,
fish,
hopper,
humanoid,
humanoid_CMU,
lqr,
manipulator,
pendulum,
point_mass,
quadruped,
reacher,
stacker,
swimmer,
walker,
)
# Find all domains imported.
_DOMAINS = {
name: module
for name, module in locals().items()
if inspect.ismodule(module) and hasattr(module, "SUITE")
}
def _get_tasks(tag):
"""Returns a sequence of (domain name, task name) pairs for the given tag."""
result = []
for domain_name in sorted(_DOMAINS.keys()):
domain = _DOMAINS[domain_name]
if tag is None:
tasks_in_domain = domain.SUITE
else:
tasks_in_domain = domain.SUITE.tagged(tag)
for task_name in tasks_in_domain.keys():
result.append((domain_name, task_name))
return tuple(result)
def _get_tasks_by_domain(tasks):
"""Returns a dict mapping from task name to a tuple of domain names."""
result = collections.defaultdict(list)
for domain_name, task_name in tasks:
result[domain_name].append(task_name)
return {k: tuple(v) for k, v in result.items()}
# A sequence containing all (domain name, task name) pairs.
ALL_TASKS = _get_tasks(tag=None)
# Subsets of ALL_TASKS, generated via the tag mechanism.
BENCHMARKING = _get_tasks("benchmarking")
EASY = _get_tasks("easy")
HARD = _get_tasks("hard")
EXTRA = tuple(sorted(set(ALL_TASKS) - set(BENCHMARKING)))
# A mapping from each domain name to a sequence of its task names.
TASKS_BY_DOMAIN = _get_tasks_by_domain(ALL_TASKS)
def load(
domain_name,
task_name,
task_kwargs=None,
environment_kwargs=None,
visualize_reward=False,
):
"""Returns an environment from a domain name, task name and optional settings.
```python
env = suite.load('cartpole', 'balance')
```
Args:
domain_name: A string containing the name of a domain.
task_name: A string containing the name of a task.
task_kwargs: Optional `dict` of keyword arguments for the task.
environment_kwargs: Optional `dict` specifying keyword arguments for the
environment.
visualize_reward: Optional `bool`. If `True`, object colours in rendered
frames are set to indicate the reward at each step. Default `False`.
Returns:
The requested environment.
"""
return build_environment(
domain_name, task_name, task_kwargs, environment_kwargs, visualize_reward,
)
def build_environment(
domain_name,
task_name,
task_kwargs=None,
environment_kwargs=None,
visualize_reward=False,
):
"""Returns an environment from the suite given a domain name and a task name.
Args:
domain_name: A string containing the name of a domain.
task_name: A string containing the name of a task.
task_kwargs: Optional `dict` specifying keyword arguments for the task.
environment_kwargs: Optional `dict` specifying keyword arguments for the
environment.
visualize_reward: Optional `bool`. If `True`, object colours in rendered
frames are set to indicate the reward at each step. Default `False`.
Raises:
ValueError: If the domain or task doesn't exist.
Returns:
An instance of the requested environment.
"""
if domain_name not in _DOMAINS:
raise ValueError("Domain {!r} does not exist.".format(domain_name))
domain = _DOMAINS[domain_name]
if task_name not in domain.SUITE:
raise ValueError(
"Level {!r} does not exist in domain {!r}.".format(task_name, domain_name)
)
task_kwargs = task_kwargs or {}
if environment_kwargs is not None:
task_kwargs = task_kwargs.copy()
task_kwargs["environment_kwargs"] = environment_kwargs
env = domain.SUITE[task_name](**task_kwargs)
env.task.visualize_reward = visualize_reward
return env
| 4,853 | 27.892857 | 86 | py |
mtenv | mtenv-main/local_dm_control_suite/manipulator.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Planar Manipulator domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import rewards
from dm_control.utils import xml_tools
from lxml import etree
import numpy as np
_CLOSE = 0.01 # (Meters) Distance below which a thing is considered close.
_CONTROL_TIMESTEP = 0.01 # (Seconds)
_TIME_LIMIT = 10 # (Seconds)
_P_IN_HAND = 0.1 # Probabillity of object-in-hand initial state
_P_IN_TARGET = 0.1 # Probabillity of object-in-target initial state
_ARM_JOINTS = [
"arm_root",
"arm_shoulder",
"arm_elbow",
"arm_wrist",
"finger",
"fingertip",
"thumb",
"thumbtip",
]
_ALL_PROPS = frozenset(["ball", "target_ball", "cup", "peg", "target_peg", "slot"])
SUITE = containers.TaggedTasks()
def make_model(use_peg, insert):
"""Returns a tuple containing the model XML string and a dict of assets."""
xml_string = common.read_model("manipulator.xml")
parser = etree.XMLParser(remove_blank_text=True)
mjcf = etree.XML(xml_string, parser)
# Select the desired prop.
if use_peg:
required_props = ["peg", "target_peg"]
if insert:
required_props += ["slot"]
else:
required_props = ["ball", "target_ball"]
if insert:
required_props += ["cup"]
# Remove unused props
for unused_prop in _ALL_PROPS.difference(required_props):
prop = xml_tools.find_element(mjcf, "body", unused_prop)
prop.getparent().remove(prop)
return etree.tostring(mjcf, pretty_print=True), common.ASSETS
@SUITE.add("benchmarking", "hard")
def bring_ball(
fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns manipulator bring task with the ball prop."""
use_peg = False
insert = False
physics = Physics.from_xml_string(*make_model(use_peg, insert))
task = Bring(
use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random
)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
@SUITE.add("hard")
def bring_peg(
fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns manipulator bring task with the peg prop."""
use_peg = True
insert = False
physics = Physics.from_xml_string(*make_model(use_peg, insert))
task = Bring(
use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random
)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
@SUITE.add("hard")
def insert_ball(
fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns manipulator insert task with the ball prop."""
use_peg = False
insert = True
physics = Physics.from_xml_string(*make_model(use_peg, insert))
task = Bring(
use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random
)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
@SUITE.add("hard")
def insert_peg(
fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns manipulator insert task with the peg prop."""
use_peg = True
insert = True
physics = Physics.from_xml_string(*make_model(use_peg, insert))
task = Bring(
use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random
)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
control_timestep=_CONTROL_TIMESTEP,
time_limit=time_limit,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics with additional features for the Planar Manipulator domain."""
def bounded_joint_pos(self, joint_names):
"""Returns joint positions as (sin, cos) values."""
joint_pos = self.named.data.qpos[joint_names]
return np.vstack([np.sin(joint_pos), np.cos(joint_pos)]).T
def joint_vel(self, joint_names):
"""Returns joint velocities."""
return self.named.data.qvel[joint_names]
def body_2d_pose(self, body_names, orientation=True):
"""Returns positions and/or orientations of bodies."""
if not isinstance(body_names, str):
body_names = np.array(body_names).reshape(-1, 1) # Broadcast indices.
pos = self.named.data.xpos[body_names, ["x", "z"]]
if orientation:
ori = self.named.data.xquat[body_names, ["qw", "qy"]]
return np.hstack([pos, ori])
else:
return pos
def touch(self):
return np.log1p(self.data.sensordata)
def site_distance(self, site1, site2):
site1_to_site2 = np.diff(self.named.data.site_xpos[[site2, site1]], axis=0)
return np.linalg.norm(site1_to_site2)
class Bring(base.Task):
"""A Bring `Task`: bring the prop to the target."""
def __init__(self, use_peg, insert, fully_observable, random=None):
"""Initialize an instance of the `Bring` task.
Args:
use_peg: A `bool`, whether to replace the ball prop with the peg prop.
insert: A `bool`, whether to insert the prop in a receptacle.
fully_observable: A `bool`, whether the observation should contain the
position and velocity of the object being manipulated and the target
location.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._use_peg = use_peg
self._target = "target_peg" if use_peg else "target_ball"
self._object = "peg" if self._use_peg else "ball"
self._object_joints = ["_".join([self._object, dim]) for dim in "xzy"]
self._receptacle = "slot" if self._use_peg else "cup"
self._insert = insert
self._fully_observable = fully_observable
super(Bring, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
# Local aliases
choice = self.random.choice
uniform = self.random.uniform
model = physics.named.model
data = physics.named.data
# Find a collision-free random initial configuration.
penetrating = True
while penetrating:
# Randomise angles of arm joints.
is_limited = model.jnt_limited[_ARM_JOINTS].astype(np.bool)
joint_range = model.jnt_range[_ARM_JOINTS]
lower_limits = np.where(is_limited, joint_range[:, 0], -np.pi)
upper_limits = np.where(is_limited, joint_range[:, 1], np.pi)
angles = uniform(lower_limits, upper_limits)
data.qpos[_ARM_JOINTS] = angles
# Symmetrize hand.
data.qpos["finger"] = data.qpos["thumb"]
# Randomise target location.
target_x = uniform(-0.4, 0.4)
target_z = uniform(0.1, 0.4)
if self._insert:
target_angle = uniform(-np.pi / 3, np.pi / 3)
model.body_pos[self._receptacle, ["x", "z"]] = target_x, target_z
model.body_quat[self._receptacle, ["qw", "qy"]] = [
np.cos(target_angle / 2),
np.sin(target_angle / 2),
]
else:
target_angle = uniform(-np.pi, np.pi)
model.body_pos[self._target, ["x", "z"]] = target_x, target_z
model.body_quat[self._target, ["qw", "qy"]] = [
np.cos(target_angle / 2),
np.sin(target_angle / 2),
]
# Randomise object location.
object_init_probs = [
_P_IN_HAND,
_P_IN_TARGET,
1 - _P_IN_HAND - _P_IN_TARGET,
]
init_type = choice(["in_hand", "in_target", "uniform"], p=object_init_probs)
if init_type == "in_target":
object_x = target_x
object_z = target_z
object_angle = target_angle
elif init_type == "in_hand":
physics.after_reset()
object_x = data.site_xpos["grasp", "x"]
object_z = data.site_xpos["grasp", "z"]
grasp_direction = data.site_xmat["grasp", ["xx", "zx"]]
object_angle = np.pi - np.arctan2(
grasp_direction[1], grasp_direction[0]
)
else:
object_x = uniform(-0.5, 0.5)
object_z = uniform(0, 0.7)
object_angle = uniform(0, 2 * np.pi)
data.qvel[self._object + "_x"] = uniform(-5, 5)
data.qpos[self._object_joints] = object_x, object_z, object_angle
# Check for collisions.
physics.after_reset()
penetrating = physics.data.ncon > 0
super(Bring, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns either features or only sensors (to be used with pixels)."""
obs = collections.OrderedDict()
obs["arm_pos"] = physics.bounded_joint_pos(_ARM_JOINTS)
obs["arm_vel"] = physics.joint_vel(_ARM_JOINTS)
obs["touch"] = physics.touch()
if self._fully_observable:
obs["hand_pos"] = physics.body_2d_pose("hand")
obs["object_pos"] = physics.body_2d_pose(self._object)
obs["object_vel"] = physics.joint_vel(self._object_joints)
obs["target_pos"] = physics.body_2d_pose(self._target)
return obs
def _is_close(self, distance):
return rewards.tolerance(distance, (0, _CLOSE), _CLOSE * 2)
def _peg_reward(self, physics):
"""Returns a reward for bringing the peg prop to the target."""
grasp = self._is_close(physics.site_distance("peg_grasp", "grasp"))
pinch = self._is_close(physics.site_distance("peg_pinch", "pinch"))
grasping = (grasp + pinch) / 2
bring = self._is_close(physics.site_distance("peg", "target_peg"))
bring_tip = self._is_close(physics.site_distance("target_peg_tip", "peg_tip"))
bringing = (bring + bring_tip) / 2
return max(bringing, grasping / 3)
def _ball_reward(self, physics):
"""Returns a reward for bringing the ball prop to the target."""
return self._is_close(physics.site_distance("ball", "target_ball"))
def get_reward(self, physics):
"""Returns a reward to the agent."""
if self._use_peg:
return self._peg_reward(physics)
else:
return self._ball_reward(physics)
| 12,051 | 35.521212 | 88 | py |
mtenv | mtenv-main/local_dm_control_suite/acrobot.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Acrobot domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
_DEFAULT_TIME_LIMIT = 10
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("acrobot.xml"), common.ASSETS
@SUITE.add("benchmarking")
def swingup(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns Acrobot balance task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Balance(sparse=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
@SUITE.add("benchmarking")
def swingup_sparse(
time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None
):
"""Returns Acrobot sparse balance."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Balance(sparse=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics, task, time_limit=time_limit, **environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Acrobot domain."""
def horizontal(self):
"""Returns horizontal (x) component of body frame z-axes."""
return self.named.data.xmat[["upper_arm", "lower_arm"], "xz"]
def vertical(self):
"""Returns vertical (z) component of body frame z-axes."""
return self.named.data.xmat[["upper_arm", "lower_arm"], "zz"]
def to_target(self):
"""Returns the distance from the tip to the target."""
tip_to_target = (
self.named.data.site_xpos["target"] - self.named.data.site_xpos["tip"]
)
return np.linalg.norm(tip_to_target)
def orientations(self):
"""Returns the sines and cosines of the pole angles."""
return np.concatenate((self.horizontal(), self.vertical()))
class Balance(base.Task):
"""An Acrobot `Task` to swing up and balance the pole."""
def __init__(self, sparse, random=None):
"""Initializes an instance of `Balance`.
Args:
sparse: A `bool` specifying whether to use a sparse (indicator) reward.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._sparse = sparse
super(Balance, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode.
Shoulder and elbow are set to a random position between [-pi, pi).
Args:
physics: An instance of `Physics`.
"""
physics.named.data.qpos[["shoulder", "elbow"]] = self.random.uniform(
-np.pi, np.pi, 2
)
super(Balance, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of pole orientation and angular velocities."""
obs = collections.OrderedDict()
obs["orientations"] = physics.orientations()
obs["velocity"] = physics.velocity()
return obs
def _get_reward(self, physics, sparse):
target_radius = physics.named.model.site_size["target", 0]
return rewards.tolerance(
physics.to_target(), bounds=(0, target_radius), margin=0 if sparse else 1
)
def get_reward(self, physics):
"""Returns a sparse or a smooth reward, as specified in the constructor."""
return self._get_reward(physics, sparse=self._sparse)
| 4,670 | 34.386364 | 85 | py |
mtenv | mtenv-main/local_dm_control_suite/humanoid_CMU.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Humanoid_CMU Domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
_DEFAULT_TIME_LIMIT = 20
_CONTROL_TIMESTEP = 0.02
# Height of head above which stand reward is 1.
_STAND_HEIGHT = 1.4
# Horizontal speeds above which move reward is 1.
_WALK_SPEED = 1
_RUN_SPEED = 10
SUITE = containers.TaggedTasks()
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("humanoid_CMU.xml"), common.ASSETS
@SUITE.add()
def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Stand task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = HumanoidCMU(move_speed=0, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add()
def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Run task."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = HumanoidCMU(move_speed=_RUN_SPEED, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the humanoid_CMU domain."""
def thorax_upright(self):
"""Returns projection from y-axes of thorax to the z-axes of world."""
return self.named.data.xmat["thorax", "zy"]
def head_height(self):
"""Returns the height of the head."""
return self.named.data.xpos["head", "z"]
def center_of_mass_position(self):
"""Returns position of the center-of-mass."""
return self.named.data.subtree_com["thorax"]
def center_of_mass_velocity(self):
"""Returns the velocity of the center-of-mass."""
return self.named.data.sensordata["thorax_subtreelinvel"].copy()
def torso_vertical_orientation(self):
"""Returns the z-projection of the thorax orientation matrix."""
return self.named.data.xmat["thorax", ["zx", "zy", "zz"]]
def joint_angles(self):
"""Returns the state without global orientation or position."""
return self.data.qpos[7:].copy() # Skip the 7 DoFs of the free root joint.
def extremities(self):
"""Returns end effector positions in egocentric frame."""
torso_frame = self.named.data.xmat["thorax"].reshape(3, 3)
torso_pos = self.named.data.xpos["thorax"]
positions = []
for side in ("l", "r"):
for limb in ("hand", "foot"):
torso_to_limb = self.named.data.xpos[side + limb] - torso_pos
positions.append(torso_to_limb.dot(torso_frame))
return np.hstack(positions)
class HumanoidCMU(base.Task):
"""A task for the CMU Humanoid."""
def __init__(self, move_speed, random=None):
"""Initializes an instance of `Humanoid_CMU`.
Args:
move_speed: A float. If this value is zero, reward is given simply for
standing up. Otherwise this specifies a target horizontal velocity for
the walking task.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._move_speed = move_speed
super(HumanoidCMU, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets a random collision-free configuration at the start of each episode.
Args:
physics: An instance of `Physics`.
"""
penetrating = True
while penetrating:
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
# Check for collisions.
physics.after_reset()
penetrating = physics.data.ncon > 0
super(HumanoidCMU, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns a set of egocentric features."""
obs = collections.OrderedDict()
obs["joint_angles"] = physics.joint_angles()
obs["head_height"] = physics.head_height()
obs["extremities"] = physics.extremities()
obs["torso_vertical"] = physics.torso_vertical_orientation()
obs["com_velocity"] = physics.center_of_mass_velocity()
obs["velocity"] = physics.velocity()
return obs
def get_reward(self, physics):
"""Returns a reward to the agent."""
standing = rewards.tolerance(
physics.head_height(),
bounds=(_STAND_HEIGHT, float("inf")),
margin=_STAND_HEIGHT / 4,
)
upright = rewards.tolerance(
physics.thorax_upright(),
bounds=(0.9, float("inf")),
sigmoid="linear",
margin=1.9,
value_at_margin=0,
)
stand_reward = standing * upright
small_control = rewards.tolerance(
physics.control(), margin=1, value_at_margin=0, sigmoid="quadratic"
).mean()
small_control = (4 + small_control) / 5
if self._move_speed == 0:
horizontal_velocity = physics.center_of_mass_velocity()[[0, 1]]
dont_move = rewards.tolerance(horizontal_velocity, margin=2).mean()
return small_control * stand_reward * dont_move
else:
com_velocity = np.linalg.norm(physics.center_of_mass_velocity()[[0, 1]])
move = rewards.tolerance(
com_velocity,
bounds=(self._move_speed, float("inf")),
margin=self._move_speed,
value_at_margin=0,
sigmoid="linear",
)
move = (5 * move + 1) / 6
return small_control * stand_reward * move
| 7,074 | 35.096939 | 85 | py |
mtenv | mtenv-main/local_dm_control_suite/hopper.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Hopper domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control import mujoco
from dm_control.rl import control
from . import base
from . import common
from dm_control.suite.utils import randomizers
from dm_control.utils import containers
from dm_control.utils import rewards
import numpy as np
SUITE = containers.TaggedTasks()
_CONTROL_TIMESTEP = 0.02 # (Seconds)
# Default duration of an episode, in seconds.
_DEFAULT_TIME_LIMIT = 20
# Minimal height of torso over foot above which stand reward is 1.
_STAND_HEIGHT = 0.6
# Hopping speed above which hop reward is 1.
_HOP_SPEED = 2
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model("hopper.xml"), common.ASSETS
@SUITE.add("benchmarking")
def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns a Hopper that strives to stand upright, balancing its pose."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Hopper(hopping=False, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
@SUITE.add("benchmarking")
def hop(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns a Hopper that strives to hop forward."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Hopper(hopping=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(
physics,
task,
time_limit=time_limit,
control_timestep=_CONTROL_TIMESTEP,
**environment_kwargs
)
class Physics(mujoco.Physics):
"""Physics simulation with additional features for the Hopper domain."""
def height(self):
"""Returns height of torso with respect to foot."""
return self.named.data.xipos["torso", "z"] - self.named.data.xipos["foot", "z"]
def speed(self):
"""Returns horizontal speed of the Hopper."""
return self.named.data.sensordata["torso_subtreelinvel"][0]
def touch(self):
"""Returns the signals from two foot touch sensors."""
return np.log1p(self.named.data.sensordata[["touch_toe", "touch_heel"]])
class Hopper(base.Task):
"""A Hopper's `Task` to train a standing and a jumping Hopper."""
def __init__(self, hopping, random=None):
"""Initialize an instance of `Hopper`.
Args:
hopping: Boolean, if True the task is to hop forwards, otherwise it is to
balance upright.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._hopping = hopping
super(Hopper, self).__init__(random=random)
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
self._timeout_progress = 0
super(Hopper, self).initialize_episode(physics)
def get_observation(self, physics):
"""Returns an observation of positions, velocities and touch sensors."""
obs = collections.OrderedDict()
# Ignores horizontal position to maintain translational invariance:
obs["position"] = physics.data.qpos[1:].copy()
obs["velocity"] = physics.velocity()
obs["touch"] = physics.touch()
return obs
def get_reward(self, physics):
"""Returns a reward applicable to the performed task."""
standing = rewards.tolerance(physics.height(), (_STAND_HEIGHT, 2))
if self._hopping:
hopping = rewards.tolerance(
physics.speed(),
bounds=(_HOP_SPEED, float("inf")),
margin=_HOP_SPEED / 2,
value_at_margin=0.5,
sigmoid="linear",
)
return standing * hopping
else:
small_control = rewards.tolerance(
physics.control(), margin=1, value_at_margin=0, sigmoid="quadratic"
).mean()
small_control = (small_control + 4) / 5
return standing * small_control
| 5,194 | 34.101351 | 87 | py |
mtenv | mtenv-main/local_dm_control_suite/common/__init__.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Functions to manage the common assets for domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from dm_control.utils import io as resources
_SUITE_DIR = os.path.dirname(os.path.dirname(__file__))
_FILENAMES = [
"./common/materials.xml",
"./common/materials_white_floor.xml",
"./common/skybox.xml",
"./common/visual.xml",
]
ASSETS = {
filename: resources.GetResource(os.path.join(_SUITE_DIR, filename))
for filename in _FILENAMES
}
def read_model(model_filename):
"""Reads a model XML file and returns its contents as a string."""
return resources.GetResource(os.path.join(_SUITE_DIR, model_filename))
| 1,387 | 32.047619 | 78 | py |
mtenv | mtenv-main/local_dm_control_suite/tests/loader_test.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the dm_control.suite loader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Internal dependencies.
from absl.testing import absltest
from dm_control import suite
from dm_control.rl import control
class LoaderTest(absltest.TestCase):
def test_load_without_kwargs(self):
env = suite.load("cartpole", "swingup")
self.assertIsInstance(env, control.Environment)
def test_load_with_kwargs(self):
env = suite.load(
"cartpole", "swingup", task_kwargs={"time_limit": 40, "random": 99}
)
self.assertIsInstance(env, control.Environment)
class LoaderConstantsTest(absltest.TestCase):
def testSuiteConstants(self):
self.assertNotEmpty(suite.BENCHMARKING)
self.assertNotEmpty(suite.EASY)
self.assertNotEmpty(suite.HARD)
self.assertNotEmpty(suite.EXTRA)
if __name__ == "__main__":
absltest.main()
| 1,640 | 30.557692 | 79 | py |
mtenv | mtenv-main/local_dm_control_suite/tests/domains_test.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_control.suite domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Internal dependencies.
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import suite
from dm_control.rl import control
import mock
import numpy as np
import six
from six.moves import range
from six.moves import zip
def uniform_random_policy(action_spec, random=None):
lower_bounds = action_spec.minimum
upper_bounds = action_spec.maximum
# Draw values between -1 and 1 for unbounded actions.
lower_bounds = np.where(np.isinf(lower_bounds), -1.0, lower_bounds)
upper_bounds = np.where(np.isinf(upper_bounds), 1.0, upper_bounds)
random_state = np.random.RandomState(random)
def policy(time_step):
del time_step # Unused.
return random_state.uniform(lower_bounds, upper_bounds)
return policy
def step_environment(env, policy, num_episodes=5, max_steps_per_episode=10):
for _ in range(num_episodes):
step_count = 0
time_step = env.reset()
yield time_step
while not time_step.last():
action = policy(time_step)
time_step = env.step(action)
step_count += 1
yield time_step
if step_count >= max_steps_per_episode:
break
def make_trajectory(domain, task, seed, **trajectory_kwargs):
env = suite.load(domain, task, task_kwargs={"random": seed})
policy = uniform_random_policy(env.action_spec(), random=seed)
return step_environment(env, policy, **trajectory_kwargs)
class DomainTest(parameterized.TestCase):
"""Tests run on all the tasks registered."""
def test_constants(self):
num_tasks = sum(len(tasks) for tasks in six.itervalues(suite.TASKS_BY_DOMAIN))
self.assertLen(suite.ALL_TASKS, num_tasks)
def _validate_observation(self, observation_dict, observation_spec):
obs = observation_dict.copy()
for name, spec in six.iteritems(observation_spec):
arr = obs.pop(name)
self.assertEqual(arr.shape, spec.shape)
self.assertEqual(arr.dtype, spec.dtype)
self.assertTrue(
np.all(np.isfinite(arr)),
msg="{!r} has non-finite value(s): {!r}".format(name, arr),
)
self.assertEmpty(
obs,
msg="Observation contains arrays(s) that are not in the spec: {!r}".format(
obs
),
)
def _validate_reward_range(self, time_step):
if time_step.first():
self.assertIsNone(time_step.reward)
else:
self.assertIsInstance(time_step.reward, float)
self.assertBetween(time_step.reward, 0, 1)
def _validate_discount(self, time_step):
if time_step.first():
self.assertIsNone(time_step.discount)
else:
self.assertIsInstance(time_step.discount, float)
self.assertBetween(time_step.discount, 0, 1)
def _validate_control_range(self, lower_bounds, upper_bounds):
for b in lower_bounds:
self.assertEqual(b, -1.0)
for b in upper_bounds:
self.assertEqual(b, 1.0)
@parameterized.parameters(*suite.ALL_TASKS)
def test_components_have_names(self, domain, task):
env = suite.load(domain, task)
model = env.physics.model
object_types_and_size_fields = [
("body", "nbody"),
("joint", "njnt"),
("geom", "ngeom"),
("site", "nsite"),
("camera", "ncam"),
("light", "nlight"),
("mesh", "nmesh"),
("hfield", "nhfield"),
("texture", "ntex"),
("material", "nmat"),
("equality", "neq"),
("tendon", "ntendon"),
("actuator", "nu"),
("sensor", "nsensor"),
("numeric", "nnumeric"),
("text", "ntext"),
("tuple", "ntuple"),
]
for object_type, size_field in object_types_and_size_fields:
for idx in range(getattr(model, size_field)):
object_name = model.id2name(idx, object_type)
self.assertNotEqual(
object_name,
"",
msg="Model {!r} contains unnamed {!r} with ID {}.".format(
model.name, object_type, idx
),
)
@parameterized.parameters(*suite.ALL_TASKS)
def test_model_has_at_least_2_cameras(self, domain, task):
env = suite.load(domain, task)
model = env.physics.model
self.assertGreaterEqual(
model.ncam,
2,
"Model {!r} should have at least 2 cameras, has {}.".format(
model.name, model.ncam
),
)
@parameterized.parameters(*suite.ALL_TASKS)
def test_task_conforms_to_spec(self, domain, task):
"""Tests that the environment timesteps conform to specifications."""
is_benchmark = (domain, task) in suite.BENCHMARKING
env = suite.load(domain, task)
observation_spec = env.observation_spec()
action_spec = env.action_spec()
# Check action bounds.
if is_benchmark:
self._validate_control_range(action_spec.minimum, action_spec.maximum)
# Step through the environment, applying random actions sampled within the
# valid range and check the observations, rewards, and discounts.
policy = uniform_random_policy(action_spec)
for time_step in step_environment(env, policy):
self._validate_observation(time_step.observation, observation_spec)
self._validate_discount(time_step)
if is_benchmark:
self._validate_reward_range(time_step)
@parameterized.parameters(*suite.ALL_TASKS)
def test_environment_is_deterministic(self, domain, task):
"""Tests that identical seeds and actions produce identical trajectories."""
seed = 0
# Iterate over two trajectories generated using identical sequences of
# random actions, and with identical task random states. Check that the
# observations, rewards, discounts and step types are identical.
trajectory1 = make_trajectory(domain=domain, task=task, seed=seed)
trajectory2 = make_trajectory(domain=domain, task=task, seed=seed)
for time_step1, time_step2 in zip(trajectory1, trajectory2):
self.assertEqual(time_step1.step_type, time_step2.step_type)
self.assertEqual(time_step1.reward, time_step2.reward)
self.assertEqual(time_step1.discount, time_step2.discount)
for key in six.iterkeys(time_step1.observation):
np.testing.assert_array_equal(
time_step1.observation[key],
time_step2.observation[key],
err_msg="Observation {!r} is not equal.".format(key),
)
def assertCorrectColors(self, physics, reward):
colors = physics.named.model.mat_rgba
for material_name in ("self", "effector", "target"):
highlight = colors[material_name + "_highlight"]
default = colors[material_name + "_default"]
blend_coef = reward ** 4
expected = blend_coef * highlight + (1.0 - blend_coef) * default
actual = colors[material_name]
err_msg = (
"Material {!r} has unexpected color.\nExpected: {!r}\n"
"Actual: {!r}".format(material_name, expected, actual)
)
np.testing.assert_array_almost_equal(expected, actual, err_msg=err_msg)
@parameterized.parameters(*suite.ALL_TASKS)
def test_visualize_reward(self, domain, task):
env = suite.load(domain, task)
env.task.visualize_reward = True
action = np.zeros(env.action_spec().shape)
with mock.patch.object(env.task, "get_reward") as mock_get_reward:
mock_get_reward.return_value = -3.0 # Rewards < 0 should be clipped.
env.reset()
mock_get_reward.assert_called_with(env.physics)
self.assertCorrectColors(env.physics, reward=0.0)
mock_get_reward.reset_mock()
mock_get_reward.return_value = 0.5
env.step(action)
mock_get_reward.assert_called_with(env.physics)
self.assertCorrectColors(env.physics, reward=mock_get_reward.return_value)
mock_get_reward.reset_mock()
mock_get_reward.return_value = 2.0 # Rewards > 1 should be clipped.
env.step(action)
mock_get_reward.assert_called_with(env.physics)
self.assertCorrectColors(env.physics, reward=1.0)
mock_get_reward.reset_mock()
mock_get_reward.return_value = 0.25
env.reset()
mock_get_reward.assert_called_with(env.physics)
self.assertCorrectColors(env.physics, reward=mock_get_reward.return_value)
@parameterized.parameters(*suite.ALL_TASKS)
def test_task_supports_environment_kwargs(self, domain, task):
env = suite.load(domain, task, environment_kwargs=dict(flat_observation=True))
# Check that the kwargs are actually passed through to the environment.
self.assertSetEqual(set(env.observation_spec()), {control.FLAT_OBSERVATION_KEY})
@parameterized.parameters(*suite.ALL_TASKS)
def test_observation_arrays_dont_share_memory(self, domain, task):
env = suite.load(domain, task)
first_timestep = env.reset()
action = np.zeros(env.action_spec().shape)
second_timestep = env.step(action)
for name, first_array in six.iteritems(first_timestep.observation):
second_array = second_timestep.observation[name]
self.assertFalse(
np.may_share_memory(first_array, second_array),
msg="Consecutive observations of {!r} may share memory.".format(name),
)
@parameterized.parameters(*suite.ALL_TASKS)
def test_observations_dont_contain_constant_elements(self, domain, task):
env = suite.load(domain, task)
trajectory = make_trajectory(
domain=domain, task=task, seed=0, num_episodes=2, max_steps_per_episode=1000
)
observations = {name: [] for name in env.observation_spec()}
for time_step in trajectory:
for name, array in six.iteritems(time_step.observation):
observations[name].append(array)
failures = []
for name, array_list in six.iteritems(observations):
# Sampling random uniform actions generally isn't sufficient to trigger
# these touch sensors.
if (
domain in ("manipulator", "stacker")
and name == "touch"
or domain == "quadruped"
and name == "force_torque"
):
continue
stacked_arrays = np.array(array_list)
is_constant = np.all(stacked_arrays == stacked_arrays[0], axis=0)
has_constant_elements = (
is_constant if np.isscalar(is_constant) else np.any(is_constant)
)
if has_constant_elements:
failures.append((name, is_constant))
self.assertEmpty(
failures,
msg="The following observation(s) contain constant elements:\n{}".format(
"\n".join(
":\t".join([name, str(is_constant)])
for (name, is_constant) in failures
)
),
)
@parameterized.parameters(*suite.ALL_TASKS)
def test_initial_state_is_randomized(self, domain, task):
env = suite.load(domain, task, task_kwargs={"random": 42})
obs1 = env.reset().observation
obs2 = env.reset().observation
self.assertFalse(
all(np.all(obs1[k] == obs2[k]) for k in obs1),
"Two consecutive initial states have identical observations.\n"
"First: {}\nSecond: {}".format(obs1, obs2),
)
if __name__ == "__main__":
absltest.main()
| 12,919 | 39.375 | 88 | py |
mtenv | mtenv-main/local_dm_control_suite/tests/lqr_test.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests specific to the LQR domain."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import unittest
# Internal dependencies.
from absl import logging
from absl.testing import absltest
from absl.testing import parameterized
from . import lqr
from . import lqr_solver
import numpy as np
from six.moves import range
class LqrTest(parameterized.TestCase):
@parameterized.named_parameters(("lqr_2_1", lqr.lqr_2_1), ("lqr_6_2", lqr.lqr_6_2))
def test_lqr_optimal_policy(self, make_env):
env = make_env()
p, k, beta = lqr_solver.solve(env)
self.assertPolicyisOptimal(env, p, k, beta)
@parameterized.named_parameters(("lqr_2_1", lqr.lqr_2_1), ("lqr_6_2", lqr.lqr_6_2))
@unittest.skipUnless(
condition=lqr_solver.sp,
reason="scipy is not available, so non-scipy DARE solver is the default.",
)
def test_lqr_optimal_policy_no_scipy(self, make_env):
env = make_env()
old_sp = lqr_solver.sp
try:
lqr_solver.sp = None # Force the solver to use the non-scipy code path.
p, k, beta = lqr_solver.solve(env)
finally:
lqr_solver.sp = old_sp
self.assertPolicyisOptimal(env, p, k, beta)
def assertPolicyisOptimal(self, env, p, k, beta):
tolerance = 1e-3
n_steps = int(math.ceil(math.log10(tolerance) / math.log10(beta)))
logging.info("%d timesteps for %g convergence.", n_steps, tolerance)
total_loss = 0.0
timestep = env.reset()
initial_state = np.hstack(
(timestep.observation["position"], timestep.observation["velocity"])
)
logging.info("Measuring total cost over %d steps.", n_steps)
for _ in range(n_steps):
x = np.hstack(
(timestep.observation["position"], timestep.observation["velocity"])
)
# u = k*x is the optimal policy
u = k.dot(x)
total_loss += 1 - (timestep.reward or 0.0)
timestep = env.step(u)
logging.info("Analytical expected total cost is .5*x^T*p*x.")
expected_loss = 0.5 * initial_state.T.dot(p).dot(initial_state)
logging.info("Comparing measured and predicted costs.")
np.testing.assert_allclose(expected_loss, total_loss, rtol=tolerance)
if __name__ == "__main__":
absltest.main()
| 3,097 | 34.204545 | 87 | py |
mtenv | mtenv-main/local_dm_control_suite/wrappers/action_noise_test.py | # Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the action noise wrapper."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Internal dependencies.
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.rl import control
from dm_control.suite.wrappers import action_noise
from dm_env import specs
import mock
import numpy as np
class ActionNoiseTest(parameterized.TestCase):
def make_action_spec(self, lower=(-1.0,), upper=(1.0,)):
lower, upper = np.broadcast_arrays(lower, upper)
return specs.BoundedArray(
shape=lower.shape, dtype=float, minimum=lower, maximum=upper
)
def make_mock_env(self, action_spec=None):
action_spec = action_spec or self.make_action_spec()
env = mock.Mock(spec=control.Environment)
env.action_spec.return_value = action_spec
return env
def assertStepCalledOnceWithCorrectAction(self, env, expected_action):
# NB: `assert_called_once_with()` doesn't support numpy arrays.
env.step.assert_called_once()
actual_action = env.step.call_args_list[0][0][0]
np.testing.assert_array_equal(expected_action, actual_action)
@parameterized.parameters(
[
dict(lower=np.r_[-1.0, 0.0], upper=np.r_[1.0, 2.0], scale=0.05),
dict(lower=np.r_[-1.0, 0.0], upper=np.r_[1.0, 2.0], scale=0.0),
dict(lower=np.r_[-1.0, 0.0], upper=np.r_[-1.0, 0.0], scale=0.05),
]
)
def test_step(self, lower, upper, scale):
seed = 0
std = scale * (upper - lower)
expected_noise = np.random.RandomState(seed).normal(scale=std)
action = np.random.RandomState(seed).uniform(lower, upper)
expected_noisy_action = np.clip(action + expected_noise, lower, upper)
task = mock.Mock(spec=control.Task)
task.random = np.random.RandomState(seed)
action_spec = self.make_action_spec(lower=lower, upper=upper)
env = self.make_mock_env(action_spec=action_spec)
env.task = task
wrapped_env = action_noise.Wrapper(env, scale=scale)
time_step = wrapped_env.step(action)
self.assertStepCalledOnceWithCorrectAction(env, expected_noisy_action)
self.assertIs(time_step, env.step(expected_noisy_action))
@parameterized.named_parameters(
[
dict(testcase_name="within_bounds", action=np.r_[-1.0], noise=np.r_[0.1]),
dict(testcase_name="below_lower", action=np.r_[-1.0], noise=np.r_[-0.1]),
dict(testcase_name="above_upper", action=np.r_[1.0], noise=np.r_[0.1]),
]
)
def test_action_clipping(self, action, noise):
lower = -1.0
upper = 1.0
expected_noisy_action = np.clip(action + noise, lower, upper)
task = mock.Mock(spec=control.Task)
task.random = mock.Mock(spec=np.random.RandomState)
task.random.normal.return_value = noise
action_spec = self.make_action_spec(lower=lower, upper=upper)
env = self.make_mock_env(action_spec=action_spec)
env.task = task
wrapped_env = action_noise.Wrapper(env)
time_step = wrapped_env.step(action)
self.assertStepCalledOnceWithCorrectAction(env, expected_noisy_action)
self.assertIs(time_step, env.step(expected_noisy_action))
@parameterized.parameters(
[
dict(lower=np.r_[-1.0, 0.0], upper=np.r_[1.0, np.inf]),
dict(lower=np.r_[np.nan, 0.0], upper=np.r_[1.0, 2.0]),
]
)
def test_error_if_action_bounds_non_finite(self, lower, upper):
action_spec = self.make_action_spec(lower=lower, upper=upper)
env = self.make_mock_env(action_spec=action_spec)
with self.assertRaisesWithLiteralMatch(
ValueError,
action_noise._BOUNDS_MUST_BE_FINITE.format(action_spec=action_spec),
):
_ = action_noise.Wrapper(env)
def test_reset(self):
env = self.make_mock_env()
wrapped_env = action_noise.Wrapper(env)
time_step = wrapped_env.reset()
env.reset.assert_called_once_with()
self.assertIs(time_step, env.reset())
def test_observation_spec(self):
env = self.make_mock_env()
wrapped_env = action_noise.Wrapper(env)
observation_spec = wrapped_env.observation_spec()
env.observation_spec.assert_called_once_with()
self.assertIs(observation_spec, env.observation_spec())
def test_action_spec(self):
env = self.make_mock_env()
wrapped_env = action_noise.Wrapper(env)
# `env.action_spec()` is called in `Wrapper.__init__()`
env.action_spec.reset_mock()
action_spec = wrapped_env.action_spec()
env.action_spec.assert_called_once_with()
self.assertIs(action_spec, env.action_spec())
@parameterized.parameters(["task", "physics", "control_timestep"])
def test_getattr(self, attribute_name):
env = self.make_mock_env()
wrapped_env = action_noise.Wrapper(env)
attr = getattr(wrapped_env, attribute_name)
self.assertIs(attr, getattr(env, attribute_name))
if __name__ == "__main__":
absltest.main()
| 5,875 | 39.805556 | 86 | py |
mtenv | mtenv-main/local_dm_control_suite/wrappers/pixels.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Wrapper that adds pixel observations to a control environment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import dm_env
from dm_env import specs
STATE_KEY = "state"
class Wrapper(dm_env.Environment):
"""Wraps a control environment and adds a rendered pixel observation."""
def __init__(
self, env, pixels_only=True, render_kwargs=None, observation_key="pixels"
):
"""Initializes a new pixel Wrapper.
Args:
env: The environment to wrap.
pixels_only: If True (default), the original set of 'state' observations
returned by the wrapped environment will be discarded, and the
`OrderedDict` of observations will only contain pixels. If False, the
`OrderedDict` will contain the original observations as well as the
pixel observations.
render_kwargs: Optional `dict` containing keyword arguments passed to the
`mujoco.Physics.render` method.
observation_key: Optional custom string specifying the pixel observation's
key in the `OrderedDict` of observations. Defaults to 'pixels'.
Raises:
ValueError: If `env`'s observation spec is not compatible with the
wrapper. Supported formats are a single array, or a dict of arrays.
ValueError: If `env`'s observation already contains the specified
`observation_key`.
"""
if render_kwargs is None:
render_kwargs = {}
wrapped_observation_spec = env.observation_spec()
if isinstance(wrapped_observation_spec, specs.Array):
self._observation_is_dict = False
invalid_keys = set([STATE_KEY])
elif isinstance(wrapped_observation_spec, collections.MutableMapping):
self._observation_is_dict = True
invalid_keys = set(wrapped_observation_spec.keys())
else:
raise ValueError("Unsupported observation spec structure.")
if not pixels_only and observation_key in invalid_keys:
raise ValueError(
"Duplicate or reserved observation key {!r}.".format(observation_key)
)
if pixels_only:
self._observation_spec = collections.OrderedDict()
elif self._observation_is_dict:
self._observation_spec = wrapped_observation_spec.copy()
else:
self._observation_spec = collections.OrderedDict()
self._observation_spec[STATE_KEY] = wrapped_observation_spec
# Extend observation spec.
pixels = env.physics.render(**render_kwargs)
pixels_spec = specs.Array(
shape=pixels.shape, dtype=pixels.dtype, name=observation_key
)
self._observation_spec[observation_key] = pixels_spec
self._env = env
self._pixels_only = pixels_only
self._render_kwargs = render_kwargs
self._observation_key = observation_key
def reset(self):
time_step = self._env.reset()
return self._add_pixel_observation(time_step)
def step(self, action):
time_step = self._env.step(action)
return self._add_pixel_observation(time_step)
def observation_spec(self):
return self._observation_spec
def action_spec(self):
return self._env.action_spec()
def _add_pixel_observation(self, time_step):
if self._pixels_only:
observation = collections.OrderedDict()
elif self._observation_is_dict:
observation = type(time_step.observation)(time_step.observation)
else:
observation = collections.OrderedDict()
observation[STATE_KEY] = time_step.observation
pixels = self._env.physics.render(**self._render_kwargs)
observation[self._observation_key] = pixels
return time_step._replace(observation=observation)
def __getattr__(self, name):
return getattr(self._env, name)
| 4,704 | 36.943548 | 85 | py |
mtenv | mtenv-main/local_dm_control_suite/wrappers/__init__.py | # Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Environment wrappers used to extend or modify environment behaviour."""
| 742 | 42.705882 | 78 | py |
mtenv | mtenv-main/local_dm_control_suite/wrappers/action_noise.py | # Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Wrapper control suite environments that adds Gaussian noise to actions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import dm_env
import numpy as np
_BOUNDS_MUST_BE_FINITE = (
"All bounds in `env.action_spec()` must be finite, got: {action_spec}"
)
class Wrapper(dm_env.Environment):
"""Wraps a control environment and adds Gaussian noise to actions."""
def __init__(self, env, scale=0.01):
"""Initializes a new action noise Wrapper.
Args:
env: The control suite environment to wrap.
scale: The standard deviation of the noise, expressed as a fraction
of the max-min range for each action dimension.
Raises:
ValueError: If any of the action dimensions of the wrapped environment are
unbounded.
"""
action_spec = env.action_spec()
if not (
np.all(np.isfinite(action_spec.minimum))
and np.all(np.isfinite(action_spec.maximum))
):
raise ValueError(_BOUNDS_MUST_BE_FINITE.format(action_spec=action_spec))
self._minimum = action_spec.minimum
self._maximum = action_spec.maximum
self._noise_std = scale * (action_spec.maximum - action_spec.minimum)
self._env = env
def step(self, action):
noisy_action = action + self._env.task.random.normal(scale=self._noise_std)
# Clip the noisy actions in place so that they fall within the bounds
# specified by the `action_spec`. Note that MuJoCo implicitly clips out-of-
# bounds control inputs, but we also clip here in case the actions do not
# correspond directly to MuJoCo actuators, or if there are other wrapper
# layers that expect the actions to be within bounds.
np.clip(noisy_action, self._minimum, self._maximum, out=noisy_action)
return self._env.step(noisy_action)
def reset(self):
return self._env.reset()
def observation_spec(self):
return self._env.observation_spec()
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
| 2,891 | 36.076923 | 84 | py |
mtenv | mtenv-main/local_dm_control_suite/wrappers/pixels_test.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the pixel wrapper."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
# Internal dependencies.
from absl.testing import absltest
from absl.testing import parameterized
from . import cartpole
from dm_control.suite.wrappers import pixels
import dm_env
from dm_env import specs
import numpy as np
class FakePhysics(object):
def render(self, *args, **kwargs):
del args
del kwargs
return np.zeros((4, 5, 3), dtype=np.uint8)
class FakeArrayObservationEnvironment(dm_env.Environment):
def __init__(self):
self.physics = FakePhysics()
def reset(self):
return dm_env.restart(np.zeros((2,)))
def step(self, action):
del action
return dm_env.transition(0.0, np.zeros((2,)))
def action_spec(self):
pass
def observation_spec(self):
return specs.Array(shape=(2,), dtype=np.float)
class PixelsTest(parameterized.TestCase):
@parameterized.parameters(True, False)
def test_dict_observation(self, pixels_only):
pixel_key = "rgb"
env = cartpole.swingup()
# Make sure we are testing the right environment for the test.
observation_spec = env.observation_spec()
self.assertIsInstance(observation_spec, collections.OrderedDict)
width = 320
height = 240
# The wrapper should only add one observation.
wrapped = pixels.Wrapper(
env,
observation_key=pixel_key,
pixels_only=pixels_only,
render_kwargs={"width": width, "height": height},
)
wrapped_observation_spec = wrapped.observation_spec()
self.assertIsInstance(wrapped_observation_spec, collections.OrderedDict)
if pixels_only:
self.assertLen(wrapped_observation_spec, 1)
self.assertEqual([pixel_key], list(wrapped_observation_spec.keys()))
else:
expected_length = len(observation_spec) + 1
self.assertLen(wrapped_observation_spec, expected_length)
expected_keys = list(observation_spec.keys()) + [pixel_key]
self.assertEqual(expected_keys, list(wrapped_observation_spec.keys()))
# Check that the added spec item is consistent with the added observation.
time_step = wrapped.reset()
rgb_observation = time_step.observation[pixel_key]
wrapped_observation_spec[pixel_key].validate(rgb_observation)
self.assertEqual(rgb_observation.shape, (height, width, 3))
self.assertEqual(rgb_observation.dtype, np.uint8)
@parameterized.parameters(True, False)
def test_single_array_observation(self, pixels_only):
pixel_key = "depth"
env = FakeArrayObservationEnvironment()
observation_spec = env.observation_spec()
self.assertIsInstance(observation_spec, specs.Array)
wrapped = pixels.Wrapper(
env, observation_key=pixel_key, pixels_only=pixels_only
)
wrapped_observation_spec = wrapped.observation_spec()
self.assertIsInstance(wrapped_observation_spec, collections.OrderedDict)
if pixels_only:
self.assertLen(wrapped_observation_spec, 1)
self.assertEqual([pixel_key], list(wrapped_observation_spec.keys()))
else:
self.assertLen(wrapped_observation_spec, 2)
self.assertEqual(
[pixels.STATE_KEY, pixel_key], list(wrapped_observation_spec.keys())
)
time_step = wrapped.reset()
depth_observation = time_step.observation[pixel_key]
wrapped_observation_spec[pixel_key].validate(depth_observation)
self.assertEqual(depth_observation.shape, (4, 5, 3))
self.assertEqual(depth_observation.dtype, np.uint8)
if __name__ == "__main__":
absltest.main()
| 4,549 | 32.455882 | 84 | py |
mtenv | mtenv-main/local_dm_control_suite/utils/parse_amc.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Parse and convert amc motion capture data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from dm_control.mujoco.wrapper import mjbindings
import numpy as np
from scipy import interpolate
from six.moves import range
mjlib = mjbindings.mjlib
MOCAP_DT = 1.0 / 120.0
CONVERSION_LENGTH = 0.056444
_CMU_MOCAP_JOINT_ORDER = (
"root0",
"root1",
"root2",
"root3",
"root4",
"root5",
"lowerbackrx",
"lowerbackry",
"lowerbackrz",
"upperbackrx",
"upperbackry",
"upperbackrz",
"thoraxrx",
"thoraxry",
"thoraxrz",
"lowerneckrx",
"lowerneckry",
"lowerneckrz",
"upperneckrx",
"upperneckry",
"upperneckrz",
"headrx",
"headry",
"headrz",
"rclaviclery",
"rclaviclerz",
"rhumerusrx",
"rhumerusry",
"rhumerusrz",
"rradiusrx",
"rwristry",
"rhandrx",
"rhandrz",
"rfingersrx",
"rthumbrx",
"rthumbrz",
"lclaviclery",
"lclaviclerz",
"lhumerusrx",
"lhumerusry",
"lhumerusrz",
"lradiusrx",
"lwristry",
"lhandrx",
"lhandrz",
"lfingersrx",
"lthumbrx",
"lthumbrz",
"rfemurrx",
"rfemurry",
"rfemurrz",
"rtibiarx",
"rfootrx",
"rfootrz",
"rtoesrx",
"lfemurrx",
"lfemurry",
"lfemurrz",
"ltibiarx",
"lfootrx",
"lfootrz",
"ltoesrx",
)
Converted = collections.namedtuple("Converted", ["qpos", "qvel", "time"])
def convert(file_name, physics, timestep):
"""Converts the parsed .amc values into qpos and qvel values and resamples.
Args:
file_name: The .amc file to be parsed and converted.
physics: The corresponding physics instance.
timestep: Desired output interval between resampled frames.
Returns:
A namedtuple with fields:
`qpos`, a numpy array containing converted positional variables.
`qvel`, a numpy array containing converted velocity variables.
`time`, a numpy array containing the corresponding times.
"""
frame_values = parse(file_name)
joint2index = {}
for name in physics.named.data.qpos.axes.row.names:
joint2index[name] = physics.named.data.qpos.axes.row.convert_key_item(name)
index2joint = {}
for joint, index in joint2index.items():
if isinstance(index, slice):
indices = range(index.start, index.stop)
else:
indices = [index]
for ii in indices:
index2joint[ii] = joint
# Convert frame_values to qpos
amcvals2qpos_transformer = Amcvals2qpos(index2joint, _CMU_MOCAP_JOINT_ORDER)
qpos_values = []
for frame_value in frame_values:
qpos_values.append(amcvals2qpos_transformer(frame_value))
qpos_values = np.stack(qpos_values) # Time by nq
# Interpolate/resample.
# Note: interpolate quaternions rather than euler angles (slerp).
# see https://en.wikipedia.org/wiki/Slerp
qpos_values_resampled = []
time_vals = np.arange(0, len(frame_values) * MOCAP_DT - 1e-8, MOCAP_DT)
time_vals_new = np.arange(0, len(frame_values) * MOCAP_DT, timestep)
while time_vals_new[-1] > time_vals[-1]:
time_vals_new = time_vals_new[:-1]
for i in range(qpos_values.shape[1]):
f = interpolate.splrep(time_vals, qpos_values[:, i])
qpos_values_resampled.append(interpolate.splev(time_vals_new, f))
qpos_values_resampled = np.stack(qpos_values_resampled) # nq by ntime
qvel_list = []
for t in range(qpos_values_resampled.shape[1] - 1):
p_tp1 = qpos_values_resampled[:, t + 1]
p_t = qpos_values_resampled[:, t]
qvel = [
(p_tp1[:3] - p_t[:3]) / timestep,
mj_quat2vel(mj_quatdiff(p_t[3:7], p_tp1[3:7]), timestep),
(p_tp1[7:] - p_t[7:]) / timestep,
]
qvel_list.append(np.concatenate(qvel))
qvel_values_resampled = np.vstack(qvel_list).T
return Converted(qpos_values_resampled, qvel_values_resampled, time_vals_new)
def parse(file_name):
"""Parses the amc file format."""
values = []
fid = open(file_name, "r")
line = fid.readline().strip()
frame_ind = 1
first_frame = True
while True:
# Parse first frame.
if first_frame and line[0] == str(frame_ind):
first_frame = False
frame_ind += 1
frame_vals = []
while True:
line = fid.readline().strip()
if not line or line == str(frame_ind):
values.append(np.array(frame_vals, dtype=np.float))
break
tokens = line.split()
frame_vals.extend(tokens[1:])
# Parse other frames.
elif line == str(frame_ind):
frame_ind += 1
frame_vals = []
while True:
line = fid.readline().strip()
if not line or line == str(frame_ind):
values.append(np.array(frame_vals, dtype=np.float))
break
tokens = line.split()
frame_vals.extend(tokens[1:])
else:
line = fid.readline().strip()
if not line:
break
return values
class Amcvals2qpos(object):
"""Callable that converts .amc values for a frame and to MuJoCo qpos format."""
def __init__(self, index2joint, joint_order):
"""Initializes a new Amcvals2qpos instance.
Args:
index2joint: List of joint angles in .amc file.
joint_order: List of joint names in MuJoco MJCF.
"""
# Root is x,y,z, then quat.
# need to get indices of qpos that order for amc default order
self.qpos_root_xyz_ind = [0, 1, 2]
self.root_xyz_ransform = (
np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]) * CONVERSION_LENGTH
)
self.qpos_root_quat_ind = [3, 4, 5, 6]
amc2qpos_transform = np.zeros((len(index2joint), len(joint_order)))
for i in range(len(index2joint)):
for j in range(len(joint_order)):
if index2joint[i] == joint_order[j]:
if "rx" in index2joint[i]:
amc2qpos_transform[i][j] = 1
elif "ry" in index2joint[i]:
amc2qpos_transform[i][j] = 1
elif "rz" in index2joint[i]:
amc2qpos_transform[i][j] = 1
self.amc2qpos_transform = amc2qpos_transform
def __call__(self, amc_val):
"""Converts a `.amc` frame to MuJoCo qpos format."""
amc_val_rad = np.deg2rad(amc_val)
qpos = np.dot(self.amc2qpos_transform, amc_val_rad)
# Root.
qpos[:3] = np.dot(self.root_xyz_ransform, amc_val[:3])
qpos_quat = euler2quat(amc_val[3], amc_val[4], amc_val[5])
qpos_quat = mj_quatprod(euler2quat(90, 0, 0), qpos_quat)
for i, ind in enumerate(self.qpos_root_quat_ind):
qpos[ind] = qpos_quat[i]
return qpos
def euler2quat(ax, ay, az):
"""Converts euler angles to a quaternion.
Note: rotation order is zyx
Args:
ax: Roll angle (deg)
ay: Pitch angle (deg).
az: Yaw angle (deg).
Returns:
A numpy array representing the rotation as a quaternion.
"""
r1 = az
r2 = ay
r3 = ax
c1 = np.cos(np.deg2rad(r1 / 2))
s1 = np.sin(np.deg2rad(r1 / 2))
c2 = np.cos(np.deg2rad(r2 / 2))
s2 = np.sin(np.deg2rad(r2 / 2))
c3 = np.cos(np.deg2rad(r3 / 2))
s3 = np.sin(np.deg2rad(r3 / 2))
q0 = c1 * c2 * c3 + s1 * s2 * s3
q1 = c1 * c2 * s3 - s1 * s2 * c3
q2 = c1 * s2 * c3 + s1 * c2 * s3
q3 = s1 * c2 * c3 - c1 * s2 * s3
return np.array([q0, q1, q2, q3])
def mj_quatprod(q, r):
quaternion = np.zeros(4)
mjlib.mju_mulQuat(quaternion, np.ascontiguousarray(q), np.ascontiguousarray(r))
return quaternion
def mj_quat2vel(q, dt):
vel = np.zeros(3)
mjlib.mju_quat2Vel(vel, np.ascontiguousarray(q), dt)
return vel
def mj_quatneg(q):
quaternion = np.zeros(4)
mjlib.mju_negQuat(quaternion, np.ascontiguousarray(q))
return quaternion
def mj_quatdiff(source, target):
return mj_quatprod(mj_quatneg(source), np.ascontiguousarray(target))
| 8,977 | 28.728477 | 83 | py |
mtenv | mtenv-main/local_dm_control_suite/utils/parse_amc_test.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for parse_amc utility."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
# Internal dependencies.
from absl.testing import absltest
from . import humanoid_CMU
from dm_control.suite.utils import parse_amc
from dm_control.utils import io as resources
_TEST_AMC_PATH = resources.GetResourceFilename(
os.path.join(os.path.dirname(__file__), "../demos/zeros.amc")
)
class ParseAMCTest(absltest.TestCase):
def test_sizes_of_parsed_data(self):
# Instantiate the humanoid environment.
env = humanoid_CMU.stand()
# Parse and convert specified clip.
converted = parse_amc.convert(
_TEST_AMC_PATH, env.physics, env.control_timestep()
)
self.assertEqual(converted.qpos.shape[0], 63)
self.assertEqual(converted.qvel.shape[0], 62)
self.assertEqual(converted.time.shape[0], converted.qpos.shape[1])
self.assertEqual(converted.qpos.shape[1], converted.qvel.shape[1] + 1)
# Parse and convert specified clip -- WITH SMALLER TIMESTEP
converted2 = parse_amc.convert(
_TEST_AMC_PATH, env.physics, 0.5 * env.control_timestep()
)
self.assertEqual(converted2.qpos.shape[0], 63)
self.assertEqual(converted2.qvel.shape[0], 62)
self.assertEqual(converted2.time.shape[0], converted2.qpos.shape[1])
self.assertEqual(converted.qpos.shape[1], converted.qvel.shape[1] + 1)
# Compare sizes of parsed objects for different timesteps
self.assertEqual(converted.qpos.shape[1] * 2, converted2.qpos.shape[1])
if __name__ == "__main__":
absltest.main()
| 2,358 | 33.188406 | 79 | py |
mtenv | mtenv-main/local_dm_control_suite/utils/randomizers.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Randomization functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from dm_control.mujoco.wrapper import mjbindings
import numpy as np
from six.moves import range
def random_limited_quaternion(random, limit):
"""Generates a random quaternion limited to the specified rotations."""
axis = random.randn(3)
axis /= np.linalg.norm(axis)
angle = random.rand() * limit
quaternion = np.zeros(4)
mjbindings.mjlib.mju_axisAngle2Quat(quaternion, axis, angle)
return quaternion
def randomize_limited_and_rotational_joints(physics, random=None):
"""Randomizes the positions of joints defined in the physics body.
The following randomization rules apply:
- Bounded joints (hinges or sliders) are sampled uniformly in the bounds.
- Unbounded hinges are samples uniformly in [-pi, pi]
- Quaternions for unlimited free joints and ball joints are sampled
uniformly on the unit 3-sphere.
- Quaternions for limited ball joints are sampled uniformly on a sector
of the unit 3-sphere.
- The linear degrees of freedom of free joints are not randomized.
Args:
physics: Instance of 'Physics' class that holds a loaded model.
random: Optional instance of 'np.random.RandomState'. Defaults to the global
NumPy random state.
"""
random = random or np.random
hinge = mjbindings.enums.mjtJoint.mjJNT_HINGE
slide = mjbindings.enums.mjtJoint.mjJNT_SLIDE
ball = mjbindings.enums.mjtJoint.mjJNT_BALL
free = mjbindings.enums.mjtJoint.mjJNT_FREE
qpos = physics.named.data.qpos
for joint_id in range(physics.model.njnt):
joint_name = physics.model.id2name(joint_id, "joint")
joint_type = physics.model.jnt_type[joint_id]
is_limited = physics.model.jnt_limited[joint_id]
range_min, range_max = physics.model.jnt_range[joint_id]
if is_limited:
if joint_type == hinge or joint_type == slide:
qpos[joint_name] = random.uniform(range_min, range_max)
elif joint_type == ball:
qpos[joint_name] = random_limited_quaternion(random, range_max)
else:
if joint_type == hinge:
qpos[joint_name] = random.uniform(-np.pi, np.pi)
elif joint_type == ball:
quat = random.randn(4)
quat /= np.linalg.norm(quat)
qpos[joint_name] = quat
elif joint_type == free:
quat = random.rand(4)
quat /= np.linalg.norm(quat)
qpos[joint_name][3:] = quat
| 3,330 | 35.604396 | 82 | py |
mtenv | mtenv-main/local_dm_control_suite/utils/__init__.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Utility functions used in the control suite."""
| 718 | 41.294118 | 78 | py |
mtenv | mtenv-main/local_dm_control_suite/utils/randomizers_test.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for randomizers.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Internal dependencies.
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import mujoco
from dm_control.mujoco.wrapper import mjbindings
from dm_control.suite.utils import randomizers
import numpy as np
from six.moves import range
mjlib = mjbindings.mjlib
class RandomizeUnlimitedJointsTest(parameterized.TestCase):
def setUp(self):
self.rand = np.random.RandomState(100)
def test_single_joint_of_each_type(self):
physics = mujoco.Physics.from_xml_string(
"""<mujoco>
<default>
<joint range="0 90" />
</default>
<worldbody>
<body>
<geom type="box" size="1 1 1"/>
<joint name="free" type="free"/>
</body>
<body>
<geom type="box" size="1 1 1"/>
<joint name="limited_hinge" type="hinge" limited="true"/>
<joint name="slide" type="slide"/>
<joint name="limited_slide" type="slide" limited="true"/>
<joint name="hinge" type="hinge"/>
</body>
<body>
<geom type="box" size="1 1 1"/>
<joint name="ball" type="ball"/>
</body>
<body>
<geom type="box" size="1 1 1"/>
<joint name="limited_ball" type="ball" limited="true"/>
</body>
</worldbody>
</mujoco>"""
)
randomizers.randomize_limited_and_rotational_joints(physics, self.rand)
self.assertNotEqual(0.0, physics.named.data.qpos["hinge"])
self.assertNotEqual(0.0, physics.named.data.qpos["limited_hinge"])
self.assertNotEqual(0.0, physics.named.data.qpos["limited_slide"])
self.assertNotEqual(0.0, np.sum(physics.named.data.qpos["ball"]))
self.assertNotEqual(0.0, np.sum(physics.named.data.qpos["limited_ball"]))
self.assertNotEqual(0.0, np.sum(physics.named.data.qpos["free"][3:]))
# Unlimited slide and the positional part of the free joint remains
# uninitialized.
self.assertEqual(0.0, physics.named.data.qpos["slide"])
self.assertEqual(0.0, np.sum(physics.named.data.qpos["free"][:3]))
def test_multiple_joints_of_same_type(self):
physics = mujoco.Physics.from_xml_string(
"""<mujoco>
<worldbody>
<body>
<geom type="box" size="1 1 1"/>
<joint name="hinge_1" type="hinge"/>
<joint name="hinge_2" type="hinge"/>
<joint name="hinge_3" type="hinge"/>
</body>
</worldbody>
</mujoco>"""
)
randomizers.randomize_limited_and_rotational_joints(physics, self.rand)
self.assertNotEqual(0.0, physics.named.data.qpos["hinge_1"])
self.assertNotEqual(0.0, physics.named.data.qpos["hinge_2"])
self.assertNotEqual(0.0, physics.named.data.qpos["hinge_3"])
self.assertNotEqual(
physics.named.data.qpos["hinge_1"], physics.named.data.qpos["hinge_2"]
)
self.assertNotEqual(
physics.named.data.qpos["hinge_2"], physics.named.data.qpos["hinge_3"]
)
self.assertNotEqual(
physics.named.data.qpos["hinge_1"], physics.named.data.qpos["hinge_3"]
)
def test_unlimited_hinge_randomization_range(self):
physics = mujoco.Physics.from_xml_string(
"""<mujoco>
<worldbody>
<body>
<geom type="box" size="1 1 1"/>
<joint name="hinge" type="hinge"/>
</body>
</worldbody>
</mujoco>"""
)
for _ in range(10):
randomizers.randomize_limited_and_rotational_joints(physics, self.rand)
self.assertBetween(physics.named.data.qpos["hinge"], -np.pi, np.pi)
def test_limited_1d_joint_limits_are_respected(self):
physics = mujoco.Physics.from_xml_string(
"""<mujoco>
<default>
<joint limited="true"/>
</default>
<worldbody>
<body>
<geom type="box" size="1 1 1"/>
<joint name="hinge" type="hinge" range="0 10"/>
<joint name="slide" type="slide" range="30 50"/>
</body>
</worldbody>
</mujoco>"""
)
for _ in range(10):
randomizers.randomize_limited_and_rotational_joints(physics, self.rand)
self.assertBetween(
physics.named.data.qpos["hinge"], np.deg2rad(0), np.deg2rad(10)
)
self.assertBetween(physics.named.data.qpos["slide"], 30, 50)
def test_limited_ball_joint_are_respected(self):
physics = mujoco.Physics.from_xml_string(
"""<mujoco>
<worldbody>
<body name="body" zaxis="1 0 0">
<geom type="box" size="1 1 1"/>
<joint name="ball" type="ball" limited="true" range="0 60"/>
</body>
</worldbody>
</mujoco>"""
)
body_axis = np.array([1.0, 0.0, 0.0])
joint_axis = np.zeros(3)
for _ in range(10):
randomizers.randomize_limited_and_rotational_joints(physics, self.rand)
quat = physics.named.data.qpos["ball"]
mjlib.mju_rotVecQuat(joint_axis, body_axis, quat)
angle_cos = np.dot(body_axis, joint_axis)
self.assertGreater(angle_cos, 0.5) # cos(60) = 0.5
if __name__ == "__main__":
absltest.main()
| 6,331 | 34.573034 | 83 | py |
mtenv | mtenv-main/local_dm_control_suite/demos/mocap_demo.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Demonstration of amc parsing for CMU mocap database.
To run the demo, supply a path to a `.amc` file:
python mocap_demo --filename='path/to/mocap.amc'
CMU motion capture clips are available at mocap.cs.cmu.edu
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
# Internal dependencies.
from absl import app
from absl import flags
from . import humanoid_CMU
from dm_control.suite.utils import parse_amc
import matplotlib.pyplot as plt
import numpy as np
FLAGS = flags.FLAGS
flags.DEFINE_string("filename", None, "amc file to be converted.")
flags.DEFINE_integer(
"max_num_frames", 90, "Maximum number of frames for plotting/playback"
)
def main(unused_argv):
env = humanoid_CMU.stand()
# Parse and convert specified clip.
converted = parse_amc.convert(FLAGS.filename, env.physics, env.control_timestep())
max_frame = min(FLAGS.max_num_frames, converted.qpos.shape[1] - 1)
width = 480
height = 480
video = np.zeros((max_frame, height, 2 * width, 3), dtype=np.uint8)
for i in range(max_frame):
p_i = converted.qpos[:, i]
with env.physics.reset_context():
env.physics.data.qpos[:] = p_i
video[i] = np.hstack(
[
env.physics.render(height, width, camera_id=0),
env.physics.render(height, width, camera_id=1),
]
)
tic = time.time()
for i in range(max_frame):
if i == 0:
img = plt.imshow(video[i])
else:
img.set_data(video[i])
toc = time.time()
clock_dt = toc - tic
tic = time.time()
# Real-time playback not always possible as clock_dt > .03
plt.pause(max(0.01, 0.03 - clock_dt)) # Need min display time > 0.0.
plt.draw()
plt.waitforbuttonpress()
if __name__ == "__main__":
flags.mark_flag_as_required("filename")
app.run(main)
| 2,633 | 28.266667 | 86 | py |
mtenv | mtenv-main/docs_src/source/conf.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath("../.."))
# -- Project information -----------------------------------------------------
import mtenv
project = "mtenv"
copyright = "2021, Facebook AI"
author = "Shagun Sodhani, Ludovic Denoyer, Pierre-Alexandre Kamienny, Olivier Delalleau"
# The full version, including alpha/beta/rc tags
release = mtenv.__version__
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosectionlabel",
"sphinx.ext.napoleon",
"sphinx.ext.viewcode",
"sphinx_copybutton",
"sphinxcontrib.bibtex",
]
bibtex_bibfiles = ["pages/bib/refs.bib"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# https://github.com/sphinx-doc/sphinx/issues/2374
autoclass_content = "both"
| 2,375 | 33.434783 | 88 | py |
libzmq | libzmq-master/perf/generate_graphs.py | #!/usr/bin/python3
#
# This script assumes that the set of CSV files produced by "generate_csv.sh" is provided as input
# and that locally there is the "results" folder.
#
# results for TCP:
INPUT_FILE_PUSHPULL_TCP_THROUGHPUT="results/pushpull_tcp_thr_results.csv"
INPUT_FILE_REQREP_TCP_LATENCY="results/reqrep_tcp_lat_results.csv"
TCP_LINK_GPBS=100
# results for INPROC:
INPUT_FILE_PUSHPULL_INPROC_THROUGHPUT="results/pushpull_inproc_thr_results.csv"
INPUT_FILE_PUBSUBPROXY_INPROC_THROUGHPUT="results/pubsubproxy_inproc_thr_results.csv"
# dependencies
#
# pip3 install matplotlib
#
import matplotlib.pyplot as plt
import numpy as np
# functions
def plot_throughput(csv_filename, title, is_tcp=False):
message_size_bytes, message_count, pps, mbps = np.loadtxt(csv_filename, delimiter=',', unpack=True)
fig, ax1 = plt.subplots()
# PPS axis
color = 'tab:red'
ax1.set_xlabel('Message size [B]')
ax1.set_ylabel('PPS [Mmsg/s]', color=color)
ax1.semilogx(message_size_bytes, pps / 1e6, label='PPS [Mmsg/s]', marker='x', color=color)
ax1.tick_params(axis='y', labelcolor=color)
# GBPS axis
color = 'tab:blue'
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('Throughput [Gb/s]', color=color)
ax2.semilogx(message_size_bytes, mbps / 1e3, label='Throughput [Gb/s]', marker='o')
if is_tcp:
ax2.set_yticks(np.arange(0, TCP_LINK_GPBS + 1, TCP_LINK_GPBS/10))
ax2.tick_params(axis='y', labelcolor=color)
ax2.grid(True)
plt.title(title)
fig.tight_layout() # otherwise the right y-label is slightly clippe
plt.savefig(csv_filename.replace('.csv', '.png'))
plt.show()
def plot_latency(csv_filename, title):
message_size_bytes, message_count, lat = np.loadtxt(csv_filename, delimiter=',', unpack=True)
plt.semilogx(message_size_bytes, lat, label='Latency [us]', marker='o')
plt.xlabel('Message size [B]')
plt.ylabel('Latency [us]')
plt.grid(True)
plt.title(title)
plt.savefig(csv_filename.replace('.csv', '.png'))
plt.show()
# main
plot_throughput(INPUT_FILE_PUSHPULL_TCP_THROUGHPUT, 'ZeroMQ PUSH/PULL socket throughput, TCP transport', is_tcp=True)
plot_throughput(INPUT_FILE_PUSHPULL_INPROC_THROUGHPUT, 'ZeroMQ PUSH/PULL socket throughput, INPROC transport')
plot_throughput(INPUT_FILE_PUBSUBPROXY_INPROC_THROUGHPUT, 'ZeroMQ PUB/SUB PROXY socket throughput, INPROC transport')
plot_latency(INPUT_FILE_REQREP_TCP_LATENCY, 'ZeroMQ REQ/REP socket latency, TCP transport')
| 2,542 | 33.364865 | 117 | py |
cwn | cwn-main/conftest.py | import pytest
def pytest_addoption(parser):
parser.addoption(
"--runslow", action="store_true", default=False, help="run slow tests",
)
parser.addoption(
"--rundata", action="store_true", default=False, help="run tests using datasets",
)
def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run")
config.addinivalue_line("markers", "data: mark test as using a dataset")
def pytest_collection_modifyitems(config, items):
skip_slow = pytest.mark.skip(reason="need --runslow option to run")
skip_data = pytest.mark.skip(reason="need --rundata option to run")
if not config.getoption("--runslow"):
for item in items:
if "slow" in item.keywords:
item.add_marker(skip_slow)
if not config.getoption("--rundata"):
for item in items:
if "data" in item.keywords:
item.add_marker(skip_data)
| 956 | 29.870968 | 89 | py |
cwn | cwn-main/definitions.py | import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) | 63 | 31 | 53 | py |
cwn | cwn-main/mp/cell_mp.py | """
Based on https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/nn/conv/message_passing.py
MIT License
Copyright (c) 2020 Matthias Fey <[email protected]>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from inspect import Parameter
from typing import List, Optional, Set
from torch_geometric.typing import Adj, Size
import torch
from torch import Tensor
from torch_sparse import SparseTensor
from torch_scatter import gather_csr, scatter, segment_csr
from torch_geometric.nn.conv.utils.helpers import expand_left
from mp.cell_mp_inspector import CellularInspector
class CochainMessagePassing(torch.nn.Module):
"""The base class for building message passing models on cochain complexes.
# TODO: Add support for co-boundary adjacencies
The class considers three types of adjacencies:
boundary, upper and lower adjacencies.
Args:
up_msg_size (int): The dimensionality of the messages coming from the upper adjacent cells.
down_msg_size (int): The dimensionality of the messages coming from the
lower adjacent cells.
aggr_up (string, optional): The aggregation scheme to use for upper-adjacencies
(:obj:`"add"`, :obj:`"mean"`, :obj:`"max"` or :obj:`None`).
(default: :obj:`"add"`)
aggr_down (string, optional): The aggregation scheme to use for lower-adjacencies
(:obj:`"add"`, :obj:`"mean"`, :obj:`"max"` or :obj:`None`).
(default: :obj:`"add"`)
aggr_boundary (string, optional): The aggregation scheme to use for boundary adjacencies.
flow (string, optional): The flow adjacency of message passing
(:obj:`"source_to_target"` or :obj:`"target_to_source"`).
(default: :obj:`"source_to_target"`)
node_dim (int, optional): The axis along which to propagate.
(default: :obj:`-2`)
boundary_msg_size (int, optional): The dimensionality of the messages coming from the
boundary cells.
use_down_msg (bool): Whether to propagate messages via the lower adjacencies.
use_boundary_msg (bool): Whether to propagate messages via the boundary adjacencies.
"""
special_args: Set[str] = {
'up_index', 'up_adj_t', 'up_index_i', 'up_index_j', 'up_size',
'up_size_i', 'up_size_j', 'up_ptr', 'agg_up_index', 'up_dim_size',
'down_index', 'down_adj_t', 'down_index_i', 'down_index_j', 'down_size',
'down_size_i', 'down_size_j', 'down_ptr', 'agg_down_index', 'down_dim_size',
'boundary_index', 'boundary_adj_t', 'boundary_index_i', 'boundary_index_j', 'boundary_size',
'boundary_size_i', 'boundary_size_j', 'boundary_ptr', 'agg_boundary_index', 'boundary_dim_size',
}
def __init__(self,
up_msg_size,
down_msg_size,
aggr_up: Optional[str] = "add",
aggr_down: Optional[str] = "add",
aggr_boundary: Optional[str] = "add",
flow: str = "source_to_target",
node_dim: int = -2,
boundary_msg_size=None,
use_down_msg=True,
use_boundary_msg=True):
super(CochainMessagePassing, self).__init__()
self.up_msg_size = up_msg_size
self.down_msg_size = down_msg_size
self.use_boundary_msg = use_boundary_msg
self.use_down_msg = use_down_msg
# Use the same out dimension for boundaries as for down adjacency by default
self.boundary_msg_size = down_msg_size if boundary_msg_size is None else boundary_msg_size
self.aggr_up = aggr_up
self.aggr_down = aggr_down
self.aggr_boundary = aggr_boundary
assert self.aggr_up in ['add', 'mean', 'max', None]
assert self.aggr_down in ['add', 'mean', 'max', None]
self.flow = flow
assert self.flow in ['source_to_target', 'target_to_source']
# This is the dimension in which nodes live in the feature matrix x.
# i.e. if x has shape [N, in_channels], then node_dim = 0 or -2
self.node_dim = node_dim
self.inspector = CellularInspector(self)
# This stores the parameters of these functions. If pop first is true
# the first parameter is not stored (I presume this is for self.)
# I presume this doesn't pop first to avoid including the self parameter multiple times.
self.inspector.inspect(self.message_up)
self.inspector.inspect(self.message_down)
self.inspector.inspect(self.message_boundary)
self.inspector.inspect(self.aggregate_up, pop_first_n=1)
self.inspector.inspect(self.aggregate_down, pop_first_n=1)
self.inspector.inspect(self.aggregate_boundary, pop_first_n=1)
self.inspector.inspect(self.message_and_aggregate_up, pop_first_n=1)
self.inspector.inspect(self.message_and_aggregate_down, pop_first_n=1)
self.inspector.inspect(self.message_and_aggregate_boundary, pop_first_n=1)
self.inspector.inspect(self.update, pop_first_n=3)
# Return the parameter name for these functions minus those specified in special_args
# TODO(Cris): Split user args by type of adjacency to make sure no bugs are introduced.
self.__user_args__ = self.inspector.keys(
['message_up', 'message_down', 'message_boundary', 'aggregate_up',
'aggregate_down', 'aggregate_boundary']).difference(self.special_args)
self.__fused_user_args__ = self.inspector.keys(
['message_and_aggregate_up',
'message_and_aggregate_down',
'message_and_aggregate_boundary']).difference(self.special_args)
self.__update_user_args__ = self.inspector.keys(
['update']).difference(self.special_args)
# Support for "fused" message passing.
self.fuse_up = self.inspector.implements('message_and_aggregate_up')
self.fuse_down = self.inspector.implements('message_and_aggregate_down')
self.fuse_boundary = self.inspector.implements('message_and_aggregate_boundary')
def __check_input_together__(self, index_up, index_down, size_up, size_down):
# If we have both up and down adjacency, then check the sizes agree.
if (index_up is not None and index_down is not None
and size_up is not None and size_down is not None):
assert size_up[0] == size_down[0]
assert size_up[1] == size_down[1]
def __check_input_separately__(self, index, size):
"""This gets an up or down index and the size of the assignment matrix"""
the_size: List[Optional[int]] = [None, None]
if isinstance(index, Tensor):
assert index.dtype == torch.long
assert index.dim() == 2
assert index.size(0) == 2
if size is not None:
the_size[0] = size[0]
the_size[1] = size[1]
return the_size
elif isinstance(index, SparseTensor):
if self.flow == 'target_to_source':
raise ValueError(
('Flow adjacency "target_to_source" is invalid for '
'message propagation via `torch_sparse.SparseTensor`. If '
'you really want to make use of a reverse message '
'passing flow, pass in the transposed sparse tensor to '
'the message passing module, e.g., `adj_t.t()`.'))
the_size[0] = index.sparse_size(1)
the_size[1] = index.sparse_size(0)
return the_size
elif index is None:
return the_size
raise ValueError(
('`MessagePassing.propagate` only supports `torch.LongTensor` of '
'shape `[2, num_messages]` or `torch_sparse.SparseTensor` for '
'argument `edge_index`.'))
def __set_size__(self, size: List[Optional[int]], dim: int, src: Tensor):
the_size = size[dim]
if the_size is None:
size[dim] = src.size(self.node_dim)
elif the_size != src.size(self.node_dim):
raise ValueError(
(f'Encountered tensor with size {src.size(self.node_dim)} in '
f'dimension {self.node_dim}, but expected size {the_size}.'))
def __lift__(self, src, index, dim):
if isinstance(index, Tensor):
index = index[dim]
return src.index_select(self.node_dim, index)
elif isinstance(index, SparseTensor):
if dim == 1:
rowptr = index.storage.rowptr()
rowptr = expand_left(rowptr, dim=self.node_dim, dims=src.dim())
return gather_csr(src, rowptr)
elif dim == 0:
col = index.storage.col()
return src.index_select(self.node_dim, col)
raise ValueError
def __collect__(self, args, index, size, adjacency, kwargs):
i, j = (1, 0) if self.flow == 'source_to_target' else (0, 1)
assert adjacency in ['up', 'down', 'boundary']
out = {}
for arg in args:
# Here the x_i and x_j parameters are automatically extracted
# from an argument having the prefix x.
if arg[-2:] not in ['_i', '_j']:
out[arg] = kwargs.get(arg, Parameter.empty)
elif index is not None:
dim = 0 if arg[-2:] == '_j' else 1
# Extract any part up to _j or _i. So for x_j extract x
if adjacency == 'up' and arg.startswith('up_'):
data = kwargs.get(arg[3:-2], Parameter.empty)
size_data = data
elif adjacency == 'down' and arg.startswith('down_'):
data = kwargs.get(arg[5:-2], Parameter.empty)
size_data = data
elif adjacency == 'boundary' and arg.startswith('boundary_'):
if dim == 0:
# We need to use the boundary attribute matrix (i.e. boundary_attr) for the features
# And we need to use the x matrix to extract the number of parent cells
data = kwargs.get('boundary_attr', Parameter.empty)
size_data = kwargs.get(arg[9:-2], Parameter.empty)
else:
data = kwargs.get(arg[9:-2], Parameter.empty)
size_data = data
else:
continue
# This was used before for the case when data is supplied directly
# as (x_i, x_j) as opposed to a matrix X [N, in_channels]
# (the 2nd case is handled by the next if)
if isinstance(data, (tuple, list)):
raise ValueError('This format is not supported for cellular message passing')
# This is the usual case when we get a feature matrix of shape [N, in_channels]
if isinstance(data, Tensor):
# Same size checks as above.
self.__set_size__(size, dim, size_data)
# Select the features of the nodes indexed by i or j from the data matrix
data = self.__lift__(data, index, j if arg[-2:] == '_j' else i)
out[arg] = data
# Automatically builds some default parameters that can be used in the message passing
# functions as needed. This was modified to be discriminative of upper and lower adjacency.
if isinstance(index, Tensor):
out[f'{adjacency}_adj_t'] = None
out[f'{adjacency}_ptr'] = None
out[f'{adjacency}_index'] = index
out[f'{adjacency}_index_i'] = index[i]
out[f'{adjacency}_index_j'] = index[j]
elif isinstance(index, SparseTensor):
out['edge_index'] = None
out[f'{adjacency}_adj_t'] = index
out[f'{adjacency}_index_i'] = index.storage.row()
out[f'{adjacency}_index_j'] = index.storage.col()
out[f'{adjacency}_ptr'] = index.storage.rowptr()
out[f'{adjacency}_weight'] = index.storage.value()
out[f'{adjacency}_attr'] = index.storage.value()
out[f'{adjacency}_type'] = index.storage.value()
# We need this if in contrast to pyg because index can be None for some adjacencies.
if isinstance(index, Tensor) or isinstance(index, SparseTensor):
# This is the old `index` argument used for aggregation of the messages.
out[f'agg_{adjacency}_index'] = out[f'{adjacency}_index_i']
out[f'{adjacency}_size'] = size
out[f'{adjacency}_size_i'] = size[1] or size[0]
out[f'{adjacency}_size_j'] = size[0] or size[1]
out[f'{adjacency}_dim_size'] = out[f'{adjacency}_size_i']
return out
def get_msg_and_agg_func(self, adjacency):
if adjacency == 'up':
return self.message_and_aggregate_up
if adjacency == 'down':
return self.message_and_aggregate_down
elif adjacency == 'boundary':
return self.message_and_aggregate_boundary
else:
return None
def get_msg_func(self, adjacency):
if adjacency == 'up':
return self.message_up
elif adjacency == 'down':
return self.message_down
elif adjacency == 'boundary':
return self.message_boundary
else:
return None
def get_agg_func(self, adjacency):
if adjacency == 'up':
return self.aggregate_up
elif adjacency == 'down':
return self.aggregate_down
elif adjacency == 'boundary':
return self.aggregate_boundary
else:
return None
def get_fuse_boolean(self, adjacency):
if adjacency == 'up':
return self.fuse_up
elif adjacency == 'down':
return self.fuse_down
elif adjacency == 'boundary':
return self.fuse_boundary
else:
return None
def __message_and_aggregate__(self, index: Adj,
adjacency: str,
size: List[Optional[int]] = None,
**kwargs):
assert adjacency in ['up', 'down', 'boundary']
# Fused message and aggregation
fuse = self.get_fuse_boolean(adjacency)
if isinstance(index, SparseTensor) and fuse:
# Collect the objects to pass to the function params in __user_arg.
coll_dict = self.__collect__(self.__fused_user_args__, index, size, adjacency, kwargs)
# message and aggregation are fused in a single function
msg_aggr_kwargs = self.inspector.distribute(
f'message_and_aggregate_{adjacency}', coll_dict)
message_and_aggregate = self.get_msg_and_agg_func(adjacency)
return message_and_aggregate(index, **msg_aggr_kwargs)
# Otherwise, run message and aggregation in separation.
elif isinstance(index, Tensor) or not fuse:
# Collect the objects to pass to the function params in __user_arg.
coll_dict = self.__collect__(self.__user_args__, index, size, adjacency, kwargs)
# Up message and aggregation
msg_kwargs = self.inspector.distribute(f'message_{adjacency}', coll_dict)
message = self.get_msg_func(adjacency)
out = message(**msg_kwargs)
# import pdb; pdb.set_trace()
aggr_kwargs = self.inspector.distribute(f'aggregate_{adjacency}', coll_dict)
aggregate = self.get_agg_func(adjacency)
return aggregate(out, **aggr_kwargs)
def propagate(self, up_index: Optional[Adj],
down_index: Optional[Adj],
boundary_index: Optional[Adj], # The None default does not work here!
up_size: Size = None,
down_size: Size = None,
boundary_size: Size = None,
**kwargs):
"""The initial call to start propagating messages."""
up_size = self.__check_input_separately__(up_index, up_size)
down_size = self.__check_input_separately__(down_index, down_size)
boundary_size = self.__check_input_separately__(boundary_index, boundary_size)
self.__check_input_together__(up_index, down_index, up_size, down_size)
up_out, down_out = None, None
# Up messaging and aggregation
if up_index is not None:
up_out = self.__message_and_aggregate__(up_index, 'up', up_size, **kwargs)
# Down messaging and aggregation
if self.use_down_msg and down_index is not None:
down_out = self.__message_and_aggregate__(down_index, 'down', down_size, **kwargs)
# boundary messaging and aggregation
boundary_out = None
if self.use_boundary_msg and 'boundary_attr' in kwargs and kwargs['boundary_attr'] is not None:
boundary_out = self.__message_and_aggregate__(boundary_index, 'boundary', boundary_size, **kwargs)
coll_dict = {}
up_coll_dict = self.__collect__(self.__update_user_args__, up_index, up_size, 'up',
kwargs)
down_coll_dict = self.__collect__(self.__update_user_args__,
down_index, down_size, 'down', kwargs)
coll_dict.update(up_coll_dict)
coll_dict.update(down_coll_dict)
update_kwargs = self.inspector.distribute('update', coll_dict)
return self.update(up_out, down_out, boundary_out, **update_kwargs)
def message_up(self, up_x_j: Tensor, up_attr: Tensor) -> Tensor:
r"""Constructs upper messages from cell :math:`j` to cell :math:`i` for each edge in
:obj:`up_index`. This function can take any argument as input which was initially
passed to :meth:`propagate`. Furthermore, tensors passed to :meth:`propagate` can be mapped
to the respective cells :math:`i` and :math:`j` by appending :obj:`_i` or
:obj:`_j` to the variable name, *.e.g.* :obj:`x_i` and :obj:`x_j`. The parameter
:obj:`up_attr` includes the features of the shared coboundary cell.
"""
return up_x_j
def message_down(self, down_x_j: Tensor, down_attr: Tensor) -> Tensor:
r"""Constructs lower messages from cell :math:`j` to cell :math:`i` for each edge in
:obj:`down_index`. This function can take any argument as input which was initially
passed to :meth:`propagate`. Furthermore, tensors passed to :meth:`propagate` can be mapped
to the respective cells :math:`i` and :math:`j` by appending :obj:`_i` or
:obj:`_j` to the variable name, *.e.g.* :obj:`x_i` and :obj:`x_j`. The parameter
:obj:`down_attr` includes the features of the shared boundary cell.
"""
return down_x_j
def message_boundary(self, boundary_x_j: Tensor):
r"""Constructs boundary messages from cell :math:`j` to cell :math:`i` for each edge in
:obj:`boundary_index`. This function can take any argument as input which was initially
passed to :meth:`propagate`. Furthermore, tensors passed to :meth:`propagate` can be mapped
to the respective cells :math:`i` and :math:`j` by appending :obj:`_i` or
:obj:`_j` to the variable name, *.e.g.* :obj:`x_i` and :obj:`x_j`.
"""
return boundary_x_j
def aggregate_up(self, inputs: Tensor, agg_up_index: Tensor,
up_ptr: Optional[Tensor] = None,
up_dim_size: Optional[int] = None) -> Tensor:
r"""Aggregates messages from upper adjacent cells.
Takes in the output of message computation as first argument and any
argument which was initially passed to :meth:`propagate`.
By default, this function will delegate its call to scatter functions
that support "add", "mean" and "max" operations as specified in
:meth:`__init__` by the :obj:`aggr` argument.
"""
if up_ptr is not None:
up_ptr = expand_left(up_ptr, dim=self.node_dim, dims=inputs.dim())
return segment_csr(inputs, up_ptr, reduce=self.aggr_up)
else:
return scatter(inputs, agg_up_index, dim=self.node_dim, dim_size=up_dim_size,
reduce=self.aggr_up)
def aggregate_down(self, inputs: Tensor, agg_down_index: Tensor,
down_ptr: Optional[Tensor] = None,
down_dim_size: Optional[int] = None) -> Tensor:
r"""Aggregates messages from lower adjacent cells.
Takes in the output of message computation as first argument and any
argument which was initially passed to :meth:`propagate`.
By default, this function will delegate its call to scatter functions
that support "add", "mean" and "max" operations as specified in
:meth:`__init__` by the :obj:`aggr` argument.
"""
if down_ptr is not None:
down_ptr = expand_left(down_ptr, dim=self.node_dim, dims=inputs.dim())
return segment_csr(inputs, down_ptr, reduce=self.aggr_down)
else:
return scatter(inputs, agg_down_index, dim=self.node_dim, dim_size=down_dim_size,
reduce=self.aggr_down)
def aggregate_boundary(self, inputs: Tensor, agg_boundary_index: Tensor,
boundary_ptr: Optional[Tensor] = None,
boundary_dim_size: Optional[int] = None) -> Tensor:
r"""Aggregates messages from the boundary cells.
Takes in the output of message computation as first argument and any
argument which was initially passed to :meth:`propagate`.
By default, this function will delegate its call to scatter functions
that support "add", "mean" and "max" operations as specified in
:meth:`__init__` by the :obj:`aggr` argument.
"""
# import pdb; pdb.set_trace()
if boundary_ptr is not None:
down_ptr = expand_left(boundary_ptr, dim=self.node_dim, dims=inputs.dim())
return segment_csr(inputs, down_ptr, reduce=self.aggr_boundary)
else:
return scatter(inputs, agg_boundary_index, dim=self.node_dim, dim_size=boundary_dim_size,
reduce=self.aggr_boundary)
def message_and_aggregate_up(self, up_adj_t: SparseTensor) -> Tensor:
r"""Fuses computations of :func:`message_up` and :func:`aggregate_up` into a
single function.
If applicable, this saves both time and memory since messages do not
explicitly need to be materialized.
This function will only gets called in case it is implemented and
propagation takes place based on a :obj:`torch_sparse.SparseTensor`.
"""
raise NotImplementedError
def message_and_aggregate_down(self, down_adj_t: SparseTensor) -> Tensor:
r"""Fuses computations of :func:`message_down` and :func:`aggregate_down` into a
single function.
If applicable, this saves both time and memory since messages do not
explicitly need to be materialized.
This function will only gets called in case it is implemented and
propagation takes place based on a :obj:`torch_sparse.SparseTensor`.
"""
raise NotImplementedError
def message_and_aggregate_boundary(self, boundary_adj_t: SparseTensor) -> Tensor:
r"""Fuses computations of :func:`message_boundary` and :func:`aggregate_boundary` into a
single function.
If applicable, this saves both time and memory since messages do not
explicitly need to be materialized.
This function will only gets called in case it is implemented and
propagation takes place based on a :obj:`torch_sparse.SparseTensor`.
"""
raise NotImplementedError
def update(self, up_inputs: Optional[Tensor], down_inputs: Optional[Tensor],
boundary_inputs: Optional[Tensor], x: Tensor) -> (Tensor, Tensor, Tensor):
r"""Updates cell embeddings. Takes in the output of the aggregations from different
adjacencies as the first three arguments and any argument which was initially passed to
:meth:`propagate`.
"""
if up_inputs is None:
up_inputs = torch.zeros(x.size(0), self.up_msg_size).to(device=x.device)
if down_inputs is None:
down_inputs = torch.zeros(x.size(0), self.down_msg_size).to(device=x.device)
if boundary_inputs is None:
boundary_inputs = torch.zeros(x.size(0), self.boundary_msg_size).to(device=x.device)
return up_inputs, down_inputs, boundary_inputs
class CochainMessagePassingParams:
"""A helper class storing the parameters to be supplied to the propagate function.
This object stores the equivalent of the `x` and `edge_index` objects from PyTorch Geometric.
TODO: The boundary_index and boundary_attr as well as other essential parameters are
currently passed as keyword arguments. Special parameters should be created.
Args:
x: The features of the cochain where message passing will be performed.
up_index: The index for the upper adjacencies of the cochain.
down_index: The index for the lower adjacencies of the cochain.
"""
def __init__(self, x: Tensor, up_index: Adj = None, down_index: Adj = None, **kwargs):
self.x = x
self.up_index = up_index
self.down_index = down_index
self.kwargs = kwargs
if 'boundary_index' in self.kwargs:
self.boundary_index = self.kwargs['boundary_index']
else:
self.boundary_index = None
if 'boundary_attr' in self.kwargs:
self.boundary_attr = self.kwargs['boundary_attr']
else:
self.boundary_attr = None
| 26,998 | 48 | 110 | py |
cwn | cwn-main/mp/test_layers.py | import torch
import torch.optim as optim
from mp.layers import (
DummyCellularMessagePassing, CINConv, OrientedConv, InitReduceConv, EmbedVEWithReduce)
from data.dummy_complexes import get_house_complex, get_molecular_complex
from torch import nn
from data.datasets.flow import load_flow_dataset
def test_dummy_cellular_message_passing_with_down_msg():
house_complex = get_house_complex()
v_params = house_complex.get_cochain_params(dim=0)
e_params = house_complex.get_cochain_params(dim=1)
t_params = house_complex.get_cochain_params(dim=2)
dsmp = DummyCellularMessagePassing()
v_x, e_x, t_x = dsmp.forward(v_params, e_params, t_params)
expected_v_x = torch.tensor([[12], [9], [25], [25], [23]], dtype=torch.float)
assert torch.equal(v_x, expected_v_x)
expected_e_x = torch.tensor([[10], [20], [47], [22], [42], [37]], dtype=torch.float)
assert torch.equal(e_x, expected_e_x)
expected_t_x = torch.tensor([[1]], dtype=torch.float)
assert torch.equal(t_x, expected_t_x)
def test_dummy_cellular_message_passing_with_boundary_msg():
house_complex = get_house_complex()
v_params = house_complex.get_cochain_params(dim=0)
e_params = house_complex.get_cochain_params(dim=1)
t_params = house_complex.get_cochain_params(dim=2)
dsmp = DummyCellularMessagePassing(use_boundary_msg=True, use_down_msg=False)
v_x, e_x, t_x = dsmp.forward(v_params, e_params, t_params)
expected_v_x = torch.tensor([[12], [9], [25], [25], [23]], dtype=torch.float)
assert torch.equal(v_x, expected_v_x)
expected_e_x = torch.tensor([[4], [7], [23], [9], [25], [24]], dtype=torch.float)
assert torch.equal(e_x, expected_e_x)
expected_t_x = torch.tensor([[15]], dtype=torch.float)
assert torch.equal(t_x, expected_t_x)
def test_dummy_cellular_message_passing_on_molecular_cell_complex():
molecular_complex = get_molecular_complex()
v_params = molecular_complex.get_cochain_params(dim=0)
e_params = molecular_complex.get_cochain_params(dim=1)
ring_params = molecular_complex.get_cochain_params(dim=2)
dsmp = DummyCellularMessagePassing(use_boundary_msg=True, use_down_msg=True)
v_x, e_x, ring_x = dsmp.forward(v_params, e_params, ring_params)
expected_v_x = torch.tensor([[12], [24], [24], [15], [25], [31], [47], [24]],
dtype=torch.float)
assert torch.equal(v_x, expected_v_x)
expected_e_x = torch.tensor([[35], [79], [41], [27], [66], [70], [92], [82], [53]],
dtype=torch.float)
assert torch.equal(e_x, expected_e_x)
# The first cell feature is given by 1[x] + 0[up] + (2+2)[down] + (1+2+3+4)[boundaries] = 15
# The 2nd cell is given by 2[x] + 0[up] + (1+2)[down] + (2+5+6+7+8)[boundaries] = 33
expected_ring_x = torch.tensor([[15], [33]], dtype=torch.float)
assert torch.equal(ring_x, expected_ring_x)
def test_cin_conv_training():
msg_net = nn.Sequential(nn.Linear(2, 1))
update_net = nn.Sequential(nn.Linear(1, 3))
cin_conv = CINConv(1, 1, msg_net, msg_net, update_net, 0.05)
all_params_before = []
for p in cin_conv.parameters():
all_params_before.append(p.clone().data)
assert len(all_params_before) > 0
house_complex = get_house_complex()
v_params = house_complex.get_cochain_params(dim=0)
e_params = house_complex.get_cochain_params(dim=1)
t_params = house_complex.get_cochain_params(dim=2)
yv = house_complex.get_labels(dim=0)
ye = house_complex.get_labels(dim=1)
yt = house_complex.get_labels(dim=2)
y = torch.cat([yv, ye, yt])
optimizer = optim.SGD(cin_conv.parameters(), lr=0.001)
optimizer.zero_grad()
out_v, out_e, out_t = cin_conv.forward(v_params, e_params, t_params)
out = torch.cat([out_v, out_e, out_t], dim=0)
criterion = nn.CrossEntropyLoss()
loss = criterion(out, y)
loss.backward()
optimizer.step()
all_params_after = []
for p in cin_conv.parameters():
all_params_after.append(p.clone().data)
assert len(all_params_after) == len(all_params_before)
# Check that parameters have been updated.
for i, _ in enumerate(all_params_before):
assert not torch.equal(all_params_before[i], all_params_after[i])
def test_orient_conv_on_flow_dataset():
import numpy as np
np.random.seed(4)
update_up = nn.Sequential(nn.Linear(1, 4))
update_down = nn.Sequential(nn.Linear(1, 4))
update = nn.Sequential(nn.Linear(1, 4))
train, _, G = load_flow_dataset(num_points=400, num_train=3, num_test=3)
number_of_edges = G.number_of_edges()
model = OrientedConv(1, 1, 1, update_up_nn=update_up, update_down_nn=update_down,
update_nn=update, act_fn=torch.tanh)
model.eval()
out = model.forward(train[0])
assert out.size(0) == number_of_edges
assert out.size(1) == 4
def test_init_reduce_conv_on_house_complex():
house_complex = get_house_complex()
v_params = house_complex.get_cochain_params(dim=0)
e_params = house_complex.get_cochain_params(dim=1)
t_params = house_complex.get_cochain_params(dim=2)
conv = InitReduceConv(reduce='add')
ex = conv.forward(v_params.x, e_params.boundary_index)
expected_ex = torch.tensor([[3], [5], [7], [5], [9], [8]], dtype=torch.float)
assert torch.equal(expected_ex, ex)
tx = conv.forward(e_params.x, t_params.boundary_index)
expected_tx = torch.tensor([[14]], dtype=torch.float)
assert torch.equal(expected_tx, tx)
def test_embed_with_reduce_layer_on_house_complex():
house_complex = get_house_complex()
cochains = house_complex.cochains
params = house_complex.get_all_cochain_params()
embed_layer = nn.Embedding(num_embeddings=32, embedding_dim=10)
init_reduce = InitReduceConv()
conv = EmbedVEWithReduce(embed_layer, None, init_reduce)
# Simulate the lack of features in these dimensions.
params[1].x = None
params[2].x = None
xs = conv.forward(*params)
assert len(xs) == 3
assert xs[0].dim() == 2
assert xs[0].size(0) == cochains[0].num_cells
assert xs[0].size(1) == 10
assert xs[1].size(0) == cochains[1].num_cells
assert xs[1].size(1) == 10
assert xs[2].size(0) == cochains[2].num_cells
assert xs[2].size(1) == 10
| 6,243 | 34.276836 | 96 | py |
cwn | cwn-main/mp/cell_mp_inspector.py | """
Based on https://github.com/rusty1s/pytorch_geometric/blob/76d61eaa9fc8702aa25f29dfaa5134a169d0f1f6/torch_geometric/nn/conv/utils/inspector.py
MIT License
Copyright (c) 2020 Matthias Fey <[email protected]>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import inspect
from collections import OrderedDict
from typing import Dict, Any, Callable
from torch_geometric.nn.conv.utils.inspector import Inspector
class CellularInspector(Inspector):
"""Wrapper of the PyTorch Geometric Inspector so to adapt it to our use cases."""
def __implements__(self, cls, func_name: str) -> bool:
if cls.__name__ == 'CochainMessagePassing':
return False
if func_name in cls.__dict__.keys():
return True
return any(self.__implements__(c, func_name) for c in cls.__bases__)
def inspect(self, func: Callable, pop_first_n: int = 0) -> Dict[str, Any]:
params = inspect.signature(func).parameters
params = OrderedDict(params)
for _ in range(pop_first_n):
params.popitem(last=False)
self.params[func.__name__] = params
| 2,143 | 41.88 | 142 | py |
cwn | cwn-main/mp/ring_exp_models.py | import torch
from mp.layers import SparseCINConv
from mp.nn import get_nonlinearity, get_graph_norm
from data.complex import ComplexBatch
from torch.nn import Linear, Sequential
from torch_geometric.nn import GINConv
class RingSparseCIN(torch.nn.Module):
"""
A simple cellular version of GIN employed for Ring experiments.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
max_dim: int = 2, nonlinearity='relu', train_eps=False, use_coboundaries=False,
graph_norm='id'):
super(RingSparseCIN, self).__init__()
self.max_dim = max_dim
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.init_layer = Linear(num_input_features, num_input_features)
act_module = get_nonlinearity(nonlinearity, return_module=True)
self.graph_norm = get_graph_norm(graph_norm)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
self.convs.append(
SparseCINConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None, passed_msg_up_nn=None,
passed_update_up_nn=None, passed_update_boundaries_nn=None,
train_eps=train_eps, max_dim=self.max_dim,
hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
self.lin1 = Linear(hidden, num_classes)
def reset_parameters(self):
self.init_layer.reset_parameters()
for conv in self.convs:
conv.reset_parameters()
self.lin1.reset_parameters()
def forward(self, data: ComplexBatch, include_partial=False):
xs = None
res = {}
data.nodes.x = self.init_layer(data.nodes.x)
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
xs = conv(*params)
data.set_xs(xs)
if include_partial:
for k in range(len(xs)):
res[f"layer{c}_{k}"] = xs[k]
x = xs[0]
# Extract the target node from each graph
mask = data.nodes.mask
x = self.lin1(x[mask])
if include_partial:
res['out'] = x
return x, res
return x
def __repr__(self):
return self.__class__.__name__
class RingGIN(torch.nn.Module):
def __init__(self, num_features, num_layers, hidden, num_classes, nonlinearity='relu',
graph_norm='bn'):
super(RingGIN, self).__init__()
self.nonlinearity = nonlinearity
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
self.init_linear = Linear(num_features, num_features)
self.graph_norm = get_graph_norm(graph_norm)
# BN is needed to make GIN work empirically beyond 2 layers for the ring experiments.
self.conv1 = GINConv(
Sequential(
Linear(num_features, hidden),
self.graph_norm(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
self.graph_norm(hidden),
conv_nonlinearity(),
), train_eps=False)
self.convs = torch.nn.ModuleList()
for i in range(num_layers - 1):
self.convs.append(
GINConv(
Sequential(
Linear(hidden, hidden),
self.graph_norm(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
self.graph_norm(hidden),
conv_nonlinearity(),
), train_eps=False))
self.lin1 = Linear(hidden, num_classes)
def reset_parameters(self):
self.init_linear.reset_parameters()
self.conv1.reset_parameters()
for conv in self.convs:
conv.reset_parameters()
self.lin1.reset_parameters()
def forward(self, data):
act = get_nonlinearity(self.nonlinearity, return_module=False)
x, edge_index, mask = data.x, data.edge_index, data.mask
x = self.init_linear(x)
x = act(self.conv1(x, edge_index))
for conv in self.convs:
x = conv(x, edge_index)
# Select the target node of each graph in the batch
x = x[mask]
x = self.lin1(x)
return x
def __repr__(self):
return self.__class__.__name__
| 4,771 | 35.151515 | 102 | py |
cwn | cwn-main/mp/test_permutation.py | import torch
from data.utils import compute_ring_2complex
from data.perm_utils import permute_graph, generate_permutation_matrices
from data.dummy_complexes import get_mol_testing_complex_list, convert_to_graph
from data.complex import ComplexBatch
from mp.models import SparseCIN
def test_sparse_cin0_perm_invariance_on_dummy_mol_complexes():
# Generate reference graph list
dummy_complexes = get_mol_testing_complex_list()
dummy_graphs = [convert_to_graph(complex) for complex in dummy_complexes]
for graph in dummy_graphs:
graph.edge_attr = None
# (We convert back to complexes to regenerate signals on edges and rings, fixing max_k to 7)
dummy_complexes = [compute_ring_2complex(graph.x, graph.edge_index, None, graph.num_nodes, max_k=7,
include_down_adj=False, init_method='sum', init_edges=True, init_rings=True)
for graph in dummy_graphs]
# Instantiate model
model = SparseCIN(num_input_features=1, num_classes=16, num_layers=3, hidden=32, use_coboundaries=True, nonlinearity='elu')
model.eval()
# Compute reference complex embeddings
embeddings = [model.forward(ComplexBatch.from_complex_list([comp], max_dim=comp.dimension)) for comp in dummy_complexes]
# Test invariance for multiple random permutations
for comp_emb, graph in zip(embeddings, dummy_graphs):
permutations = generate_permutation_matrices(graph.num_nodes, 5)
for perm in permutations:
permuted_graph = permute_graph(graph, perm)
permuted_comp = compute_ring_2complex(permuted_graph.x, permuted_graph.edge_index, None, permuted_graph.num_nodes,
max_k=7, include_down_adj=False, init_method='sum', init_edges=True, init_rings=True)
permuted_emb = model.forward(ComplexBatch.from_complex_list([permuted_comp], max_dim=permuted_comp.dimension))
assert torch.allclose(comp_emb, permuted_emb, atol=1e-6)
| 1,983 | 52.621622 | 127 | py |
cwn | cwn-main/mp/molec_models.py | import torch
import torch.nn.functional as F
from torch.nn import Linear, Embedding, Sequential, BatchNorm1d as BN
from torch_geometric.nn import JumpingKnowledge, GINEConv
from mp.layers import InitReduceConv, EmbedVEWithReduce, OGBEmbedVEWithReduce, SparseCINConv, CINppConv
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
from data.complex import ComplexBatch
from mp.nn import pool_complex, get_pooling_fn, get_nonlinearity, get_graph_norm
class EmbedSparseCIN(torch.nn.Module):
"""
A cellular version of GIN with some tailoring to nimbly work on molecules from the ZINC database.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, atom_types, bond_types, out_size, num_layers, hidden,
dropout_rate: float = 0.5, max_dim: int = 2, jump_mode=None, nonlinearity='relu',
readout='sum', train_eps=False, final_hidden_multiplier: int = 2,
readout_dims=(0, 1, 2), final_readout='sum', apply_dropout_before='lin2',
init_reduce='sum', embed_edge=False, embed_dim=None, use_coboundaries=False,
graph_norm='bn'):
super(EmbedSparseCIN, self).__init__()
self.max_dim = max_dim
if readout_dims is not None:
self.readout_dims = tuple([dim for dim in readout_dims if dim <= max_dim])
else:
self.readout_dims = list(range(max_dim+1))
if embed_dim is None:
embed_dim = hidden
self.v_embed_init = Embedding(atom_types, embed_dim)
self.e_embed_init = None
if embed_edge:
self.e_embed_init = Embedding(bond_types, embed_dim)
self.reduce_init = InitReduceConv(reduce=init_reduce)
self.init_conv = EmbedVEWithReduce(self.v_embed_init, self.e_embed_init, self.reduce_init)
self.final_readout = final_readout
self.dropout_rate = dropout_rate
self.apply_dropout_before = apply_dropout_before
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.readout = readout
self.graph_norm = get_graph_norm(graph_norm)
act_module = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = embed_dim if i == 0 else hidden
self.convs.append(
SparseCINConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None,
passed_msg_up_nn=None, passed_update_up_nn=None,
passed_update_boundaries_nn=None, train_eps=train_eps, max_dim=self.max_dim,
hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
self.lin1s = torch.nn.ModuleList()
for _ in range(max_dim + 1):
if jump_mode == 'cat':
# These layers don't use a bias. Then, in case a level is not present the output
# is just zero and it is not given by the biases.
self.lin1s.append(Linear(num_layers * hidden, final_hidden_multiplier * hidden,
bias=False))
else:
self.lin1s.append(Linear(hidden, final_hidden_multiplier * hidden))
self.lin2 = Linear(final_hidden_multiplier * hidden, out_size)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.init_conv.reset_parameters()
self.lin1s.reset_parameters()
self.lin2.reset_parameters()
def jump_complex(self, jump_xs):
# Perform JumpingKnowledge at each level of the complex
xs = []
for jumpx in jump_xs:
xs += [self.jump(jumpx)]
return xs
def forward(self, data: ComplexBatch, include_partial=False):
act = get_nonlinearity(self.nonlinearity, return_module=False)
xs, jump_xs = None, None
res = {}
# Check input node/edge features are scalars.
assert data.cochains[0].x.size(-1) == 1
if 1 in data.cochains and data.cochains[1].x is not None:
assert data.cochains[1].x.size(-1) == 1
# Embed and populate higher-levels
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
xs = list(self.init_conv(*params))
# Apply dropout on the input features like all models do on ZINC.
for i, x in enumerate(xs):
xs[i] = F.dropout(xs[i], p=self.dropout_rate, training=self.training)
data.set_xs(xs)
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
start_to_process = 0
xs = conv(*params, start_to_process=start_to_process)
data.set_xs(xs)
if include_partial:
for k in range(len(xs)):
res[f"layer{c}_{k}"] = xs[k]
if self.jump_mode is not None:
if jump_xs is None:
jump_xs = [[] for _ in xs]
for i, x in enumerate(xs):
jump_xs[i] += [x]
if self.jump_mode is not None:
xs = self.jump_complex(jump_xs)
xs = pool_complex(xs, data, self.max_dim, self.readout)
# Select the dimensions we want at the end.
xs = [xs[i] for i in self.readout_dims]
if include_partial:
for k in range(len(xs)):
res[f"pool_{k}"] = xs[k]
new_xs = []
for i, x in enumerate(xs):
if self.apply_dropout_before == 'lin1':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
new_xs.append(act(self.lin1s[self.readout_dims[i]](x)))
x = torch.stack(new_xs, dim=0)
if self.apply_dropout_before == 'final_readout':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
if self.final_readout == 'mean':
x = x.mean(0)
elif self.final_readout == 'sum':
x = x.sum(0)
else:
raise NotImplementedError
if self.apply_dropout_before not in ['lin1', 'final_readout']:
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
if include_partial:
res['out'] = x
return x, res
return x
def __repr__(self):
return self.__class__.__name__
class EmbedCINpp(EmbedSparseCIN):
"""
Inherit from EmbedSparseCIN and add messages from lower adj cells
"""
def __init__(self, atom_types, bond_types, out_size, num_layers, hidden,
dropout_rate: float = 0.5, max_dim: int = 2, jump_mode=None,
nonlinearity='relu', readout='sum', train_eps=False,
final_hidden_multiplier: int = 2, readout_dims=(0, 1, 2),
final_readout='sum', apply_dropout_before='lin2', init_reduce='sum',
embed_edge=False, embed_dim=None, use_coboundaries=False, graph_norm='bn'):
super(EmbedCINpp, self).__init__(atom_types, bond_types, out_size, num_layers,
hidden, dropout_rate, max_dim, jump_mode,
nonlinearity, readout, train_eps,
final_hidden_multiplier, readout_dims,
final_readout, apply_dropout_before,
init_reduce, embed_edge, embed_dim,
use_coboundaries, graph_norm)
self.convs = torch.nn.ModuleList() #reset convs to use CINppConv instead of SparseCINConv
act_module = get_nonlinearity(nonlinearity, return_module=True)
if embed_dim is None:
embed_dim = hidden
for i in range(num_layers):
layer_dim = embed_dim if i == 0 else hidden
self.convs.append(
CINppConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None,
passed_msg_up_nn=None, passed_msg_down_nn=None, passed_update_up_nn=None,
passed_update_down_nn=None, passed_update_boundaries_nn=None, train_eps=train_eps,
max_dim=self.max_dim, hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
class OGBEmbedSparseCIN(torch.nn.Module):
"""
A cellular version of GIN with some tailoring to nimbly work on molecules from the ogbg-mol* dataset.
It uses OGB atom and bond encoders.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, out_size, num_layers, hidden, dropout_rate: float = 0.5,
indropout_rate: float = 0.0, max_dim: int = 2, jump_mode=None,
nonlinearity='relu', readout='sum', train_eps=False, final_hidden_multiplier: int = 2,
readout_dims=(0, 1, 2), final_readout='sum', apply_dropout_before='lin2',
init_reduce='sum', embed_edge=False, embed_dim=None, use_coboundaries=False,
graph_norm='bn'):
super(OGBEmbedSparseCIN, self).__init__()
self.max_dim = max_dim
if readout_dims is not None:
self.readout_dims = tuple([dim for dim in readout_dims if dim <= max_dim])
else:
self.readout_dims = list(range(max_dim+1))
if embed_dim is None:
embed_dim = hidden
self.v_embed_init = AtomEncoder(embed_dim)
self.e_embed_init = None
if embed_edge:
self.e_embed_init = BondEncoder(embed_dim)
self.reduce_init = InitReduceConv(reduce=init_reduce)
self.init_conv = OGBEmbedVEWithReduce(self.v_embed_init, self.e_embed_init, self.reduce_init)
self.final_readout = final_readout
self.dropout_rate = dropout_rate
self.in_dropout_rate = indropout_rate
self.apply_dropout_before = apply_dropout_before
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.readout = readout
act_module = get_nonlinearity(nonlinearity, return_module=True)
self.graph_norm = get_graph_norm(graph_norm)
for i in range(num_layers):
layer_dim = embed_dim if i == 0 else hidden
self.convs.append(
SparseCINConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None,
passed_msg_up_nn=None, passed_update_up_nn=None,
passed_update_boundaries_nn=None, train_eps=train_eps, max_dim=self.max_dim,
hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
self.lin1s = torch.nn.ModuleList()
for _ in range(max_dim + 1):
if jump_mode == 'cat':
# These layers don't use a bias. Then, in case a level is not present the output
# is just zero and it is not given by the biases.
self.lin1s.append(Linear(num_layers * hidden, final_hidden_multiplier * hidden,
bias=False))
else:
self.lin1s.append(Linear(hidden, final_hidden_multiplier * hidden))
self.lin2 = Linear(final_hidden_multiplier * hidden, out_size)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.init_conv.reset_parameters()
self.lin1s.reset_parameters()
self.lin2.reset_parameters()
def jump_complex(self, jump_xs):
# Perform JumpingKnowledge at each level of the complex
xs = []
for jumpx in jump_xs:
xs += [self.jump(jumpx)]
return xs
def forward(self, data: ComplexBatch, include_partial=False):
act = get_nonlinearity(self.nonlinearity, return_module=False)
xs, jump_xs = None, None
res = {}
# Embed and populate higher-levels
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
xs = list(self.init_conv(*params))
# Apply dropout on the input features
for i, x in enumerate(xs):
xs[i] = F.dropout(xs[i], p=self.in_dropout_rate, training=self.training)
data.set_xs(xs)
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
start_to_process = 0
xs = conv(*params, start_to_process=start_to_process)
# Apply dropout on the output of the conv layer
for i, x in enumerate(xs):
xs[i] = F.dropout(xs[i], p=self.dropout_rate, training=self.training)
data.set_xs(xs)
if include_partial:
for k in range(len(xs)):
res[f"layer{c}_{k}"] = xs[k]
if self.jump_mode is not None:
if jump_xs is None:
jump_xs = [[] for _ in xs]
for i, x in enumerate(xs):
jump_xs[i] += [x]
if self.jump_mode is not None:
xs = self.jump_complex(jump_xs)
xs = pool_complex(xs, data, self.max_dim, self.readout)
# Select the dimensions we want at the end.
xs = [xs[i] for i in self.readout_dims]
if include_partial:
for k in range(len(xs)):
res[f"pool_{k}"] = xs[k]
new_xs = []
for i, x in enumerate(xs):
if self.apply_dropout_before == 'lin1':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
new_xs.append(act(self.lin1s[self.readout_dims[i]](x)))
x = torch.stack(new_xs, dim=0)
if self.apply_dropout_before == 'final_readout':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
if self.final_readout == 'mean':
x = x.mean(0)
elif self.final_readout == 'sum':
x = x.sum(0)
else:
raise NotImplementedError
if self.apply_dropout_before not in ['lin1', 'final_readout']:
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
if include_partial:
res['out'] = x
return x, res
return x
def __repr__(self):
return self.__class__.__name__
class OGBEmbedCINpp(OGBEmbedSparseCIN):
"""
Inherit from EmbedSparseCIN and add messages from lower adj cells
"""
def __init__(self, out_size, num_layers, hidden, dropout_rate: float = 0.5,
indropout_rate: float = 0, max_dim: int = 2, jump_mode=None,
nonlinearity='relu', readout='sum', train_eps=False,
final_hidden_multiplier: int = 2, readout_dims=(0, 1, 2),
final_readout='sum', apply_dropout_before='lin2', init_reduce='sum',
embed_edge=False, embed_dim=None, use_coboundaries=False, graph_norm='bn'):
super().__init__(out_size, num_layers, hidden, dropout_rate, indropout_rate,
max_dim, jump_mode, nonlinearity, readout, train_eps,
final_hidden_multiplier, readout_dims, final_readout,
apply_dropout_before, init_reduce, embed_edge, embed_dim,
use_coboundaries, graph_norm)
self.convs = torch.nn.ModuleList() #reset convs to use CINppConv instead of SparseCINConv
act_module = get_nonlinearity(nonlinearity, return_module=True)
if embed_dim is None:
embed_dim = hidden
for i in range(num_layers):
layer_dim = embed_dim if i == 0 else hidden
self.convs.append(
CINppConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None,
passed_msg_up_nn=None, passed_msg_down_nn=None, passed_update_up_nn=None,
passed_update_down_nn=None, passed_update_boundaries_nn=None, train_eps=train_eps,
max_dim=self.max_dim, hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
class EmbedSparseCINNoRings(torch.nn.Module):
"""
CIN model on cell complexes up to dimension 1 (edges). It does not make use of rings.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, atom_types, bond_types, out_size, num_layers, hidden,
dropout_rate: float = 0.5, nonlinearity='relu',
readout='sum', train_eps=False, final_hidden_multiplier: int = 2,
final_readout='sum', apply_dropout_before='lin2',
init_reduce='sum', embed_edge=False, embed_dim=None, use_coboundaries=False,
graph_norm='bn'):
super(EmbedSparseCINNoRings, self).__init__()
self.max_dim = 1
self.readout_dims = [0, 1]
if embed_dim is None:
embed_dim = hidden
self.v_embed_init = Embedding(atom_types, embed_dim)
self.e_embed_init = None
if embed_edge:
self.e_embed_init = Embedding(bond_types, embed_dim)
self.reduce_init = InitReduceConv(reduce=init_reduce)
self.init_conv = EmbedVEWithReduce(self.v_embed_init, self.e_embed_init, self.reduce_init)
self.final_readout = final_readout
self.dropout_rate = dropout_rate
self.apply_dropout_before = apply_dropout_before
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.readout = readout
self.graph_norm = get_graph_norm(graph_norm)
act_module = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = embed_dim if i == 0 else hidden
self.convs.append(
SparseCINConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None,
passed_msg_up_nn=None, passed_update_up_nn=None,
passed_update_boundaries_nn=None, train_eps=train_eps, max_dim=self.max_dim,
hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
self.lin1s = torch.nn.ModuleList()
for _ in range(self.max_dim + 1):
self.lin1s.append(Linear(hidden, final_hidden_multiplier * hidden))
self.lin2 = Linear(final_hidden_multiplier * hidden, out_size)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
self.init_conv.reset_parameters()
self.lin1s.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data: ComplexBatch):
act = get_nonlinearity(self.nonlinearity, return_module=False)
# Check input node/edge features are scalars.
assert data.cochains[0].x.size(-1) == 1
if 1 in data.cochains and data.cochains[1].x is not None:
assert data.cochains[1].x.size(-1) == 1
# Extract node and edge params
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
# Make the upper index of the edges None to ignore the rings. Even though max_dim = 1
# our current code does extract upper adjacencies for edges if rings are present.
if len(params) > 1:
params[1].up_index = None
# Embed the node and edge features
xs = list(self.init_conv(*params))
# Apply dropout on the input features
for i, x in enumerate(xs):
xs[i] = F.dropout(xs[i], p=self.dropout_rate, training=self.training)
data.set_xs(xs)
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
if len(params) > 1:
params[1].up_index = None
xs = conv(*params)
data.set_xs(xs)
xs = pool_complex(xs, data, self.max_dim, self.readout)
# Select the dimensions we want at the end.
xs = [xs[i] for i in self.readout_dims]
new_xs = []
for i, x in enumerate(xs):
if self.apply_dropout_before == 'lin1':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
new_xs.append(act(self.lin1s[self.readout_dims[i]](x)))
x = torch.stack(new_xs, dim=0)
if self.apply_dropout_before == 'final_readout':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
if self.final_readout == 'mean':
x = x.mean(0)
elif self.final_readout == 'sum':
x = x.sum(0)
else:
raise NotImplementedError
if self.apply_dropout_before not in ['lin1', 'final_readout']:
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
class EmbedGIN(torch.nn.Module):
"""
GIN with cell complex inputs to test our pipeline.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, atom_types, bond_types, out_size, num_layers, hidden,
dropout_rate: float = 0.5, nonlinearity='relu',
readout='sum', train_eps=False, apply_dropout_before='lin2',
init_reduce='sum', embed_edge=False, embed_dim=None):
super(EmbedGIN, self).__init__()
self.max_dim = 1
if embed_dim is None:
embed_dim = hidden
self.v_embed_init = Embedding(atom_types, embed_dim)
self.e_embed_init = None
if embed_edge:
self.e_embed_init = Embedding(bond_types, embed_dim)
self.reduce_init = InitReduceConv(reduce=init_reduce)
self.init_conv = EmbedVEWithReduce(self.v_embed_init, self.e_embed_init, self.reduce_init)
self.dropout_rate = dropout_rate
self.apply_dropout_before = apply_dropout_before
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.pooling_fn = get_pooling_fn(readout)
act_module = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = embed_dim if i == 0 else hidden
self.convs.append(
GINEConv(
# Here we instantiate and pass the MLP performing the `update` function.
Sequential(
Linear(layer_dim, hidden),
BN(hidden),
act_module(),
Linear(hidden, hidden),
BN(hidden),
act_module(),
), train_eps=train_eps))
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, out_size)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
self.init_conv.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data: ComplexBatch):
act = get_nonlinearity(self.nonlinearity, return_module=False)
# Check input node/edge features are scalars.
assert data.cochains[0].x.size(-1) == 1
if 1 in data.cochains and data.cochains[1].x is not None:
assert data.cochains[1].x.size(-1) == 1
# Extract node and edge params
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
# Embed the node and edge features
xs = list(self.init_conv(*params))
# Apply dropout on the input node features
xs[0] = F.dropout(xs[0], p=self.dropout_rate, training=self.training)
data.set_xs(xs)
# We fetch input parameters only at dimension 0 (nodes)
params = data.get_all_cochain_params(max_dim=0, include_down_features=False)[0]
x = params.x
edge_index = params.up_index
edge_attr = params.kwargs['up_attr']
# For the edge case when no edges are present.
if edge_index is None:
edge_index = torch.LongTensor([[], []])
edge_attr = torch.FloatTensor([[0]*x.size(-1)])
for c, conv in enumerate(self.convs):
x = conv(x=x, edge_index=edge_index, edge_attr=edge_attr)
# Pool only over nodes
batch_size = data.cochains[0].batch.max() + 1
x = self.pooling_fn(x, data.nodes.batch, size=batch_size)
if self.apply_dropout_before == 'lin1':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = act(self.lin1(x))
if self.apply_dropout_before in ['final_readout', 'lin2']:
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
| 26,185 | 42.140033 | 106 | py |
cwn | cwn-main/mp/test_models.py | import torch
import pytest
import itertools
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from mp.models import CIN0, EdgeCIN0, SparseCIN
from data.data_loading import DataLoader, load_dataset
def test_cin_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2, 3]
bs = list(range(2, len(data_list)+1))
params = itertools.product(bs, dims, dims)
for batch_size, batch_max_dim, model_max_dim in params:
if batch_max_dim > model_max_dim:
continue
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
model = CIN0(num_input_features=1, num_classes=3, num_layers=3, hidden=5, jump_mode='cat',
max_dim=model_max_dim)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_preds = []
for batch in data_loader:
batched_pred = model.forward(batch)
batched_preds.append(batched_pred)
batched_preds = torch.cat(batched_preds, dim=0)
preds = []
for complex in data_list:
pred = model.forward(ComplexBatch.from_complex_list([complex], max_dim=batch_max_dim))
preds.append(pred)
preds = torch.cat(preds, dim=0)
# Atol was reduced from 1e-6 to 1e-5 to remove flakiness.
assert (preds.size() == batched_preds.size())
assert torch.allclose(preds, batched_preds, atol=1e-5)
def test_edge_cin0_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
for top_features in [True, False]:
data_loader = DataLoader(data_list, batch_size=4)
model = EdgeCIN0(num_input_features=1, num_classes=3, num_layers=3, hidden=5,
jump_mode='cat', include_top_features=top_features)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_preds = []
for batch in data_loader:
batched_pred = model.forward(batch)
batched_preds.append(batched_pred)
batched_preds = torch.cat(batched_preds, dim=0)
preds = []
for complex in data_list:
pred = model.forward(ComplexBatch.from_complex_list([complex]))
preds.append(pred)
preds = torch.cat(preds, dim=0)
assert torch.allclose(preds, batched_preds, atol=1e-6)
def test_edge_cin0_model_with_batching_while_including_top_features_and_max_dim_one():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
data_loader = DataLoader(data_list, batch_size=4)
model1 = EdgeCIN0(num_input_features=1, num_classes=3, num_layers=3, hidden=5,
jump_mode='cat', include_top_features=True)
# We use the model in eval mode to avoid problems with batch norm.
model1.eval()
batched_preds = []
for batch in data_loader:
batched_pred = model1.forward(batch)
batched_preds.append(batched_pred)
batched_preds1 = torch.cat(batched_preds, dim=0)
model2 = EdgeCIN0(num_input_features=1, num_classes=3, num_layers=3, hidden=5,
jump_mode='cat', include_top_features=False)
# We use the model in eval mode to avoid problems with batch norm.
model2.eval()
batched_preds = []
for batch in data_loader:
batched_pred = model2.forward(batch)
batched_preds.append(batched_pred)
batched_preds2 = torch.cat(batched_preds, dim=0)
# Check excluding the top features providea a different
# output compared to the model that includes them.
assert not torch.equal(batched_preds1, batched_preds2)
def test_cin_model_with_batching_over_complexes_missing_two_cells():
"""Check this runs without errors"""
data_list = get_testing_complex_list()
data_loader = DataLoader(data_list, batch_size=2)
# Run using a model that works up to two_cells.
model = CIN0(num_input_features=1, num_classes=3, num_layers=3, hidden=5, max_dim=2,
jump_mode='max')
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
preds1 = []
for batch in data_loader:
out = model.forward(batch)
preds1.append(out)
preds1 = torch.cat(preds1, dim=0)
# Run using a model that works up to edges.
model = CIN0(num_input_features=1, num_classes=3, num_layers=3, hidden=5, max_dim=1,
jump_mode='max')
model.eval()
data_loader = DataLoader(data_list, batch_size=2, max_dim=1)
preds2 = []
for batch in data_loader:
out = model.forward(batch)
preds2.append(out)
preds2 = torch.cat(preds2, dim=0)
# Make sure the two outputs are different. The model using two_cells set the two_cell outputs
# to zero, so the output of the readout should also be different.
assert not torch.equal(preds1, preds2)
def test_sparse_cin0_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2, 3]
bs = list(range(2, len(data_list)+1))
params = itertools.product(bs, dims, dims)
torch.manual_seed(0)
for batch_size, batch_max_dim, model_max_dim in params:
if batch_max_dim > model_max_dim:
continue
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
model = SparseCIN(num_input_features=1, num_classes=3, num_layers=3, hidden=5,
jump_mode='cat', max_dim=model_max_dim)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_res = {}
for batch in data_loader:
batched_pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in batched_res:
batched_res[key] = []
batched_res[key].append(res[key])
for key in batched_res:
batched_res[key] = torch.cat(batched_res[key], dim=0)
unbatched_res = {}
for complex in data_list:
# print(f"Complex dim {complex.dimension}")
pred, res = model.forward(ComplexBatch.from_complex_list([complex],
max_dim=batch_max_dim),
include_partial=True)
for key in res:
if key not in unbatched_res:
unbatched_res[key] = []
unbatched_res[key].append(res[key])
for key in unbatched_res:
unbatched_res[key] = torch.cat(unbatched_res[key], dim=0)
for key in set(list(unbatched_res.keys()) + list(batched_res.keys())):
assert torch.allclose(unbatched_res[key], batched_res[key], atol=1e-6), (
print(key, torch.max(torch.abs(unbatched_res[key] - batched_res[key]))))
@pytest.mark.data
def test_sparse_cin0_model_with_batching_on_proteins():
"""Check this runs without errors and that batching and no batching produce the same output."""
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
assert len(dataset) == 1113
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
max_dim = 3
torch.manual_seed(0)
data_loader = DataLoader(dataset, batch_size=32, max_dim=max_dim)
model = SparseCIN(num_input_features=dataset.num_features_in_dim(0),
num_classes=2, num_layers=3, hidden=5, jump_mode=None, max_dim=max_dim)
model.eval()
batched_res = {}
for batch in data_loader:
batched_pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in batched_res:
batched_res[key] = []
batched_res[key].append(res[key])
for key in batched_res:
batched_res[key] = torch.cat(batched_res[key], dim=0)
unbatched_res = {}
for complex in dataset:
# print(f"Complex dim {complex.dimension}")
pred, res = model.forward(ComplexBatch.from_complex_list([complex], max_dim=max_dim),
include_partial=True)
for key in res:
if key not in unbatched_res:
unbatched_res[key] = []
unbatched_res[key].append(res[key])
for key in unbatched_res:
unbatched_res[key] = torch.cat(unbatched_res[key], dim=0)
for key in set(list(unbatched_res.keys()) + list(batched_res.keys())):
assert torch.allclose(unbatched_res[key], batched_res[key], atol=1e-6), (
print(key, torch.max(torch.abs(unbatched_res[key] - batched_res[key]))))
| 9,019 | 37.712446 | 99 | py |
cwn | cwn-main/mp/layers.py | import torch
from typing import Any, Callable, Optional
from torch import Tensor
from mp.cell_mp import CochainMessagePassing, CochainMessagePassingParams
from torch_geometric.nn.inits import reset
from torch.nn import Linear, Sequential, BatchNorm1d as BN, Identity
from data.complex import Cochain
from torch_scatter import scatter
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
from abc import ABC, abstractmethod
class DummyCochainMessagePassing(CochainMessagePassing):
"""This is a dummy parameter-free message passing model used for testing."""
def __init__(self, up_msg_size, down_msg_size, boundary_msg_size=None,
use_boundary_msg=False, use_down_msg=True):
super(DummyCochainMessagePassing, self).__init__(up_msg_size, down_msg_size,
boundary_msg_size=boundary_msg_size,
use_boundary_msg=use_boundary_msg,
use_down_msg=use_down_msg)
def message_up(self, up_x_j: Tensor, up_attr: Tensor) -> Tensor:
# (num_up_adj, x_feature_dim) + (num_up_adj, up_feat_dim)
# We assume the feature dim is the same across al levels
return up_x_j + up_attr
def message_down(self, down_x_j: Tensor, down_attr: Tensor) -> Tensor:
# (num_down_adj, x_feature_dim) + (num_down_adj, down_feat_dim)
# We assume the feature dim is the same across al levels
return down_x_j + down_attr
def forward(self, cochain: CochainMessagePassingParams):
up_out, down_out, boundary_out = self.propagate(cochain.up_index, cochain.down_index,
cochain.boundary_index, x=cochain.x,
up_attr=cochain.kwargs['up_attr'],
down_attr=cochain.kwargs['down_attr'],
boundary_attr=cochain.kwargs['boundary_attr'])
# down or boundary will be zero if one of them is not used.
return cochain.x + up_out + down_out + boundary_out
class DummyCellularMessagePassing(torch.nn.Module):
def __init__(self, input_dim=1, max_dim: int = 2, use_boundary_msg=False, use_down_msg=True):
super(DummyCellularMessagePassing, self).__init__()
self.max_dim = max_dim
self.mp_levels = torch.nn.ModuleList()
for dim in range(max_dim+1):
mp = DummyCochainMessagePassing(input_dim, input_dim, boundary_msg_size=input_dim,
use_boundary_msg=use_boundary_msg, use_down_msg=use_down_msg)
self.mp_levels.append(mp)
def forward(self, *cochain_params: CochainMessagePassingParams):
assert len(cochain_params) <= self.max_dim+1
out = []
for dim in range(len(cochain_params)):
out.append(self.mp_levels[dim].forward(cochain_params[dim]))
return out
class CINCochainConv(CochainMessagePassing):
"""This is a dummy parameter-free message passing model used for testing."""
def __init__(self, up_msg_size: int, down_msg_size: int,
msg_up_nn: Callable, msg_down_nn: Callable, update_nn: Callable,
eps: float = 0., train_eps: bool = False):
super(CINCochainConv, self).__init__(up_msg_size, down_msg_size, use_boundary_msg=False)
self.msg_up_nn = msg_up_nn
self.msg_down_nn = msg_down_nn
self.update_nn = update_nn
self.initial_eps = eps
if train_eps:
self.eps = torch.nn.Parameter(torch.Tensor([eps]))
else:
self.register_buffer('eps', torch.Tensor([eps]))
self.reset_parameters()
def forward(self, cochain: CochainMessagePassingParams):
out_up, out_down, _ = self.propagate(cochain.up_index, cochain.down_index,
None, x=cochain.x,
up_attr=cochain.kwargs['up_attr'],
down_attr=cochain.kwargs['down_attr'])
out_up += (1 + self.eps) * cochain.x
out_down += (1 + self.eps) * cochain.x
return self.update_nn(out_up + out_down)
def reset_parameters(self):
reset(self.msg_up_nn)
reset(self.msg_down_nn)
reset(self.update_nn)
self.eps.data.fill_(self.initial_eps)
def message_up(self, up_x_j: Tensor, up_attr: Tensor) -> Tensor:
if up_attr is not None:
x = torch.cat([up_x_j, up_attr], dim=-1)
return self.msg_up_nn(x)
else:
return self.msg_up_nn(up_x_j)
def message_down(self, down_x_j: Tensor, down_attr: Tensor) -> Tensor:
x = torch.cat([down_x_j, down_attr], dim=-1)
return self.msg_down_nn(x)
class CINConv(torch.nn.Module):
def __init__(self, up_msg_size: int, down_msg_size: int,
msg_up_nn: Callable, msg_down_nn: Callable, update_nn: Callable,
eps: float = 0., train_eps: bool = False, max_dim: int = 2):
super(CINConv, self).__init__()
self.max_dim = max_dim
self.mp_levels = torch.nn.ModuleList()
for dim in range(max_dim+1):
mp = CINCochainConv(up_msg_size, down_msg_size,
msg_up_nn, msg_down_nn, update_nn, eps, train_eps)
self.mp_levels.append(mp)
def forward(self, *cochain_params: CochainMessagePassingParams):
assert len(cochain_params) <= self.max_dim+1
out = []
for dim in range(len(cochain_params)):
out.append(self.mp_levels[dim].forward(cochain_params[dim]))
return out
class EdgeCINConv(torch.nn.Module):
"""
CIN convolutional layer which performs cochain message passing only
_up to_ 1-dimensional cells (edges).
"""
def __init__(self, up_msg_size: int, down_msg_size: int,
v_msg_up_nn: Callable, e_msg_down_nn: Callable, e_msg_up_nn: Callable,
v_update_nn: Callable, e_update_nn: Callable, eps: float = 0., train_eps=False):
super(EdgeCINConv, self).__init__()
self.max_dim = 1
self.mp_levels = torch.nn.ModuleList()
v_mp = CINCochainConv(up_msg_size, down_msg_size,
v_msg_up_nn, lambda *args: None, v_update_nn, eps, train_eps)
e_mp = CINCochainConv(up_msg_size, down_msg_size,
e_msg_up_nn, e_msg_down_nn, e_update_nn, eps, train_eps)
self.mp_levels.extend([v_mp, e_mp])
def forward(self, *cochain_params: CochainMessagePassingParams):
assert len(cochain_params) <= self.max_dim+1
out = []
for dim in range(len(cochain_params)):
out.append(self.mp_levels[dim].forward(cochain_params[dim]))
return out
class SparseCINCochainConv(CochainMessagePassing):
"""This is a CIN Cochain layer that operates of boundaries and upper adjacent cells."""
def __init__(self, dim: int,
up_msg_size: int,
down_msg_size: int,
boundary_msg_size: Optional[int],
msg_up_nn: Callable,
msg_boundaries_nn: Callable,
update_up_nn: Callable,
update_boundaries_nn: Callable,
combine_nn: Callable,
eps: float = 0.,
train_eps: bool = False):
super(SparseCINCochainConv, self).__init__(up_msg_size, down_msg_size, boundary_msg_size=boundary_msg_size,
use_down_msg=False)
self.dim = dim
self.msg_up_nn = msg_up_nn
self.msg_boundaries_nn = msg_boundaries_nn
self.update_up_nn = update_up_nn
self.update_boundaries_nn = update_boundaries_nn
self.combine_nn = combine_nn
self.initial_eps = eps
if train_eps:
self.eps1 = torch.nn.Parameter(torch.Tensor([eps]))
self.eps2 = torch.nn.Parameter(torch.Tensor([eps]))
else:
self.register_buffer('eps1', torch.Tensor([eps]))
self.register_buffer('eps2', torch.Tensor([eps]))
self.reset_parameters()
def forward(self, cochain: CochainMessagePassingParams):
out_up, _, out_boundaries = self.propagate(cochain.up_index, cochain.down_index,
cochain.boundary_index, x=cochain.x,
up_attr=cochain.kwargs['up_attr'],
boundary_attr=cochain.kwargs['boundary_attr'])
# As in GIN, we can learn an injective update function for each multi-set
out_up += (1 + self.eps1) * cochain.x
out_boundaries += (1 + self.eps2) * cochain.x
out_up = self.update_up_nn(out_up)
out_boundaries = self.update_boundaries_nn(out_boundaries)
# We need to combine the two such that the output is injective
# Because the cross product of countable spaces is countable, then such a function exists.
# And we can learn it with another MLP.
return self.combine_nn(torch.cat([out_up, out_boundaries], dim=-1))
def reset_parameters(self):
reset(self.msg_up_nn)
reset(self.msg_boundaries_nn)
reset(self.update_up_nn)
reset(self.update_boundaries_nn)
reset(self.combine_nn)
self.eps1.data.fill_(self.initial_eps)
self.eps2.data.fill_(self.initial_eps)
def message_up(self, up_x_j: Tensor, up_attr: Tensor) -> Tensor:
return self.msg_up_nn((up_x_j, up_attr))
def message_boundary(self, boundary_x_j: Tensor) -> Tensor:
return self.msg_boundaries_nn(boundary_x_j)
class CINppCochainConv(SparseCINCochainConv):
"""CINppCochainConv
"""
def __init__(self, dim: int, up_msg_size: int, down_msg_size: int, boundary_msg_size: int,
msg_up_nn: Callable[..., Any], msg_boundaries_nn: Callable[..., Any], msg_down_nn: Callable[..., Any],
update_up_nn: Callable[..., Any], update_boundaries_nn: Callable[..., Any], update_down_nn: Callable[..., Any],
combine_nn: Callable[..., Any], eps: float = 0, train_eps: bool = False):
super(CINppCochainConv, self).__init__(dim, up_msg_size, down_msg_size, boundary_msg_size,
msg_up_nn, msg_boundaries_nn,
update_up_nn, update_boundaries_nn,
combine_nn, eps, train_eps)
self.msg_down_nn = msg_down_nn
self.update_down_nn = update_down_nn
if train_eps:
self.eps3 = torch.nn.Parameter(torch.Tensor([eps]))
else:
self.register_buffer('eps3', torch.Tensor([eps]))
reset(self.msg_down_nn)
reset(self.update_down_nn)
self.eps3.data.fill_(self.initial_eps)
def message_down(self, down_x_j: Tensor, down_attr: Tensor) -> Tensor:
return self.msg_down_nn((down_x_j, down_attr))
def forward(self, cochain: CochainMessagePassingParams):
out_up, out_down, out_boundaries = self.propagate(cochain.up_index, cochain.down_index,
cochain.boundary_index, x=cochain.x,
up_attr=cochain.kwargs['up_attr'],
boundary_attr=cochain.kwargs['boundary_attr'])
# As in GIN, we can learn an injective update function for each multi-set
out_up += (1 + self.eps1) * cochain.x
out_down += (1 + self.eps2) * cochain.x
out_boundaries += (1 + self.eps3) * cochain.x
out_up = self.update_up_nn(out_up)
out_down = self.update_down_nn(out_down)
out_boundaries = self.update_boundaries_nn(out_boundaries)
# We need to combine the three such that the output is injective
# Because the cross product of countable spaces is countable, then such a function exists.
# And we can learn it with another MLP.
return self.combine_nn(torch.cat([out_up, out_down, out_boundaries], dim=-1))
class Catter(torch.nn.Module):
def __init__(self):
super(Catter, self).__init__()
def forward(self, x):
return torch.cat(x, dim=-1)
class SparseCINConv(torch.nn.Module):
"""A cellular version of GIN which performs message passing from cellular upper
neighbors and boundaries, but not from lower neighbors (hence why "Sparse")
"""
# TODO: Refactor the way we pass networks externally to allow for different networks per dim.
def __init__(self, up_msg_size: int, down_msg_size: int, boundary_msg_size: Optional[int],
passed_msg_up_nn: Optional[Callable], passed_msg_boundaries_nn: Optional[Callable],
passed_update_up_nn: Optional[Callable],
passed_update_boundaries_nn: Optional[Callable],
eps: float = 0., train_eps: bool = False, max_dim: int = 2,
graph_norm=BN, use_coboundaries=False, **kwargs):
super(SparseCINConv, self).__init__()
self.max_dim = max_dim
self.mp_levels = torch.nn.ModuleList()
for dim in range(max_dim+1):
msg_up_nn = passed_msg_up_nn
if msg_up_nn is None:
if use_coboundaries:
msg_up_nn = Sequential(
Catter(),
Linear(kwargs['layer_dim'] * 2, kwargs['layer_dim']),
kwargs['act_module']())
else:
msg_up_nn = lambda xs: xs[0]
msg_boundaries_nn = passed_msg_boundaries_nn
if msg_boundaries_nn is None:
msg_boundaries_nn = lambda x: x
update_up_nn = passed_update_up_nn
if update_up_nn is None:
update_up_nn = Sequential(
Linear(kwargs['layer_dim'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module'](),
Linear(kwargs['hidden'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']()
)
update_boundaries_nn = passed_update_boundaries_nn
if update_boundaries_nn is None:
update_boundaries_nn = Sequential(
Linear(kwargs['layer_dim'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module'](),
Linear(kwargs['hidden'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']()
)
combine_nn = Sequential(
Linear(kwargs['hidden']*2, kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']())
mp = SparseCINCochainConv(dim, up_msg_size, down_msg_size, boundary_msg_size=boundary_msg_size,
msg_up_nn=msg_up_nn, msg_boundaries_nn=msg_boundaries_nn, update_up_nn=update_up_nn,
update_boundaries_nn=update_boundaries_nn, combine_nn=combine_nn, eps=eps,
train_eps=train_eps)
self.mp_levels.append(mp)
def forward(self, *cochain_params: CochainMessagePassingParams, start_to_process=0):
assert len(cochain_params) <= self.max_dim+1
out = []
for dim in range(len(cochain_params)):
if dim < start_to_process:
out.append(cochain_params[dim].x)
else:
out.append(self.mp_levels[dim].forward(cochain_params[dim]))
return out
class CINppConv(SparseCINConv):
"""
"""
def __init__(self, up_msg_size: int, down_msg_size: int, boundary_msg_size: Optional[int],
passed_msg_up_nn: Optional[Callable], passed_msg_down_nn: Optional[Callable],
passed_msg_boundaries_nn: Optional[Callable],
passed_update_up_nn: Optional[Callable],
passed_update_down_nn: Optional[Callable],
passed_update_boundaries_nn: Optional[Callable],
eps: float = 0., train_eps: bool = False, max_dim: int = 2,
graph_norm=BN, use_coboundaries=False, **kwargs):
super(CINppConv, self).__init__(up_msg_size, down_msg_size, boundary_msg_size,
passed_msg_up_nn, passed_msg_boundaries_nn,
passed_update_up_nn, passed_update_boundaries_nn,
eps, train_eps, max_dim, graph_norm, use_coboundaries, **kwargs)
self.max_dim = max_dim
self.mp_levels = torch.nn.ModuleList()
for dim in range(max_dim+1):
msg_up_nn = passed_msg_up_nn
if msg_up_nn is None:
if use_coboundaries:
msg_up_nn = Sequential(
Catter(),
Linear(kwargs['layer_dim'] * 2, kwargs['layer_dim']),
kwargs['act_module']())
else:
msg_up_nn = lambda xs: xs[0]
msg_down_nn = passed_msg_down_nn
if msg_down_nn is None:
if use_coboundaries:
msg_down_nn = Sequential(
Catter(),
Linear(kwargs['layer_dim'] * 2, kwargs['layer_dim']),
kwargs['act_module']())
else:
msg_down_nn = lambda xs: xs[0]
msg_boundaries_nn = passed_msg_boundaries_nn
if msg_boundaries_nn is None:
msg_boundaries_nn = lambda x: x
update_up_nn = passed_update_up_nn
if update_up_nn is None:
update_up_nn = Sequential(
Linear(kwargs['layer_dim'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module'](),
Linear(kwargs['hidden'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']()
)
update_down_nn = passed_update_down_nn
if update_down_nn is None:
update_down_nn = Sequential(
Linear(kwargs['layer_dim'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module'](),
Linear(kwargs['hidden'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']()
)
update_boundaries_nn = passed_update_boundaries_nn
if update_boundaries_nn is None:
update_boundaries_nn = Sequential(
Linear(kwargs['layer_dim'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module'](),
Linear(kwargs['hidden'], kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']()
)
combine_nn = Sequential(
Linear(kwargs['hidden']*3, kwargs['hidden']),
graph_norm(kwargs['hidden']),
kwargs['act_module']())
mp = CINppCochainConv(dim, up_msg_size, down_msg_size, boundary_msg_size=boundary_msg_size,
msg_up_nn=msg_up_nn, msg_down_nn=msg_down_nn, msg_boundaries_nn=msg_boundaries_nn, update_up_nn=update_up_nn,
update_down_nn=update_down_nn, update_boundaries_nn=update_boundaries_nn, combine_nn=combine_nn, eps=eps,
train_eps=train_eps)
self.mp_levels.append(mp)
class OrientedConv(CochainMessagePassing):
def __init__(self, dim: int, up_msg_size: int, down_msg_size: int,
update_up_nn: Optional[Callable], update_down_nn: Optional[Callable],
update_nn: Optional[Callable], act_fn, orient=True):
super(OrientedConv, self).__init__(up_msg_size, down_msg_size, use_boundary_msg=False)
self.dim = dim
self.update_up_nn = update_up_nn
self.update_down_nn = update_down_nn
self.update_nn = update_nn
self.act_fn = act_fn
self.orient = orient
def forward(self, cochain: Cochain):
assert len(cochain.upper_orient) == cochain.upper_index.size(1)
assert len(cochain.lower_orient) == cochain.lower_index.size(1)
assert cochain.upper_index.max() < len(cochain.x)
assert cochain.lower_index.max() < len(cochain.x)
out_up, out_down, _ = self.propagate(cochain.upper_index, cochain.lower_index, None, x=cochain.x,
up_attr=cochain.upper_orient.view(-1, 1), down_attr=cochain.lower_orient.view(-1, 1))
out_up = self.update_up_nn(out_up)
out_down = self.update_down_nn(out_down)
x = self.update_nn(cochain.x)
return self.act_fn(x + out_up + out_down)
def reset_parameters(self):
reset(self.update_up_nn)
reset(self.update_down_nn)
reset(self.update_nn)
# TODO: As a temporary hack, we pass the orientation through the up and down attributes.
def message_up(self, up_x_j: Tensor, up_attr: Tensor) -> Tensor:
if self.orient:
return up_x_j * up_attr
return up_x_j
def message_down(self, down_x_j: Tensor, down_attr: Tensor) -> Tensor:
if self.orient:
return down_x_j * down_attr
return down_x_j
class InitReduceConv(torch.nn.Module):
def __init__(self, reduce='add'):
"""
Args:
reduce (str): Way to aggregate boundaries. Can be "sum, add, mean, min, max"
"""
super(InitReduceConv, self).__init__()
self.reduce = reduce
def forward(self, boundary_x, boundary_index):
features = boundary_x.index_select(0, boundary_index[0])
out_size = boundary_index[1, :].max() + 1
return scatter(features, boundary_index[1], dim=0, dim_size=out_size, reduce=self.reduce)
class AbstractEmbedVEWithReduce(torch.nn.Module, ABC):
def __init__(self,
v_embed_layer: Callable,
e_embed_layer: Optional[Callable],
init_reduce: InitReduceConv):
"""
Args:
v_embed_layer: Layer to embed the integer features of the vertices
e_embed_layer: Layer (potentially None) to embed the integer features of the edges.
init_reduce: Layer to initialise the 2D cell features and potentially the edge features.
"""
super(AbstractEmbedVEWithReduce, self).__init__()
self.v_embed_layer = v_embed_layer
self.e_embed_layer = e_embed_layer
self.init_reduce = init_reduce
@abstractmethod
def _prepare_v_inputs(self, v_params):
pass
@abstractmethod
def _prepare_e_inputs(self, e_params):
pass
def forward(self, *cochain_params: CochainMessagePassingParams):
assert 1 <= len(cochain_params) <= 3
v_params = cochain_params[0]
e_params = cochain_params[1] if len(cochain_params) >= 2 else None
c_params = cochain_params[2] if len(cochain_params) == 3 else None
vx = self.v_embed_layer(self._prepare_v_inputs(v_params))
out = [vx]
if e_params is None:
assert c_params is None
return out
reduced_ex = self.init_reduce(vx, e_params.boundary_index)
ex = reduced_ex
if e_params.x is not None:
ex = self.e_embed_layer(self._prepare_e_inputs(e_params))
# The output of this should be the same size as the vertex features.
assert ex.size(1) == vx.size(1)
out.append(ex)
if c_params is not None:
# We divide by two in case this was obtained from node aggregation.
# The division should not do any harm if this is an aggregation of learned embeddings.
cx = self.init_reduce(reduced_ex, c_params.boundary_index) / 2.
out.append(cx)
return out
def reset_parameters(self):
reset(self.v_embed_layer)
reset(self.e_embed_layer)
class EmbedVEWithReduce(AbstractEmbedVEWithReduce):
def __init__(self,
v_embed_layer: torch.nn.Embedding,
e_embed_layer: Optional[torch.nn.Embedding],
init_reduce: InitReduceConv):
super(EmbedVEWithReduce, self).__init__(v_embed_layer, e_embed_layer, init_reduce)
def _prepare_v_inputs(self, v_params):
assert v_params.x is not None
assert v_params.x.dim() == 2
assert v_params.x.size(1) == 1
# The embedding layer expects integers so we convert the tensor to int.
return v_params.x.squeeze(1).to(dtype=torch.long)
def _prepare_e_inputs(self, e_params):
assert self.e_embed_layer is not None
assert e_params.x.dim() == 2
assert e_params.x.size(1) == 1
# The embedding layer expects integers so we convert the tensor to int.
return e_params.x.squeeze(1).to(dtype=torch.long)
class OGBEmbedVEWithReduce(AbstractEmbedVEWithReduce):
def __init__(self,
v_embed_layer: AtomEncoder,
e_embed_layer: Optional[BondEncoder],
init_reduce: InitReduceConv):
super(OGBEmbedVEWithReduce, self).__init__(v_embed_layer, e_embed_layer, init_reduce)
def _prepare_v_inputs(self, v_params):
assert v_params.x is not None
assert v_params.x.dim() == 2
# Inputs in ogbg-mol* datasets are already long.
# This is to test the layer with other datasets.
return v_params.x.to(dtype=torch.long)
def _prepare_e_inputs(self, e_params):
assert self.e_embed_layer is not None
assert e_params.x.dim() == 2
# Inputs in ogbg-mol* datasets are already long.
# This is to test the layer with other datasets.
return e_params.x.to(dtype=torch.long)
| 26,386 | 43.422559 | 130 | py |
cwn | cwn-main/mp/nn.py | import torch
import torch.nn.functional as F
from torch_geometric.nn import global_mean_pool, global_add_pool
from torch.nn import BatchNorm1d as BN, LayerNorm as LN, Identity
def get_nonlinearity(nonlinearity, return_module=True):
if nonlinearity == 'relu':
module = torch.nn.ReLU
function = F.relu
elif nonlinearity == 'elu':
module = torch.nn.ELU
function = F.elu
elif nonlinearity == 'id':
module = torch.nn.Identity
function = lambda x: x
elif nonlinearity == 'sigmoid':
module = torch.nn.Sigmoid
function = F.sigmoid
elif nonlinearity == 'tanh':
module = torch.nn.Tanh
function = torch.tanh
else:
raise NotImplementedError('Nonlinearity {} is not currently supported.'.format(nonlinearity))
if return_module:
return module
return function
def get_pooling_fn(readout):
if readout == 'sum':
return global_add_pool
elif readout == 'mean':
return global_mean_pool
else:
raise NotImplementedError('Readout {} is not currently supported.'.format(readout))
def get_graph_norm(norm):
if norm == 'bn':
return BN
elif norm == 'ln':
return LN
elif norm == 'id':
return Identity
else:
raise ValueError(f'Graph Normalisation {norm} not currently supported')
def pool_complex(xs, data, max_dim, readout_type):
pooling_fn = get_pooling_fn(readout_type)
# All complexes have nodes so we can extract the batch size from cochains[0]
batch_size = data.cochains[0].batch.max() + 1
# The MP output is of shape [message_passing_dim, batch_size, feature_dim]
pooled_xs = torch.zeros(max_dim+1, batch_size, xs[0].size(-1),
device=batch_size.device)
for i in range(len(xs)):
# It's very important that size is supplied.
pooled_xs[i, :, :] = pooling_fn(xs[i], data.cochains[i].batch, size=batch_size)
return pooled_xs
| 2,030 | 32.295082 | 101 | py |
cwn | cwn-main/mp/models.py | import torch
import torch.nn.functional as F
from torch.nn import Linear, Sequential, BatchNorm1d as BN
from torch_geometric.nn import JumpingKnowledge
from mp.layers import (
CINConv, EdgeCINConv, SparseCINConv, CINppConv,DummyCellularMessagePassing, OrientedConv)
from mp.nn import get_nonlinearity, get_pooling_fn, pool_complex, get_graph_norm
from data.complex import ComplexBatch, CochainBatch
class CIN0(torch.nn.Module):
"""
A cellular version of GIN.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
dropout_rate: float = 0.5,
max_dim: int = 2, jump_mode=None, nonlinearity='relu', readout='sum'):
super(CIN0, self).__init__()
self.max_dim = max_dim
self.dropout_rate = dropout_rate
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.pooling_fn = get_pooling_fn(readout)
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
conv_update = Sequential(
Linear(layer_dim, hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
conv_nonlinearity(),
BN(hidden))
conv_up = Sequential(
Linear(layer_dim * 2, layer_dim),
conv_nonlinearity(),
BN(layer_dim))
conv_down = Sequential(
Linear(layer_dim * 2, layer_dim),
conv_nonlinearity(),
BN(layer_dim))
self.convs.append(
CINConv(layer_dim, layer_dim,
conv_up, conv_down, conv_update, train_eps=False, max_dim=self.max_dim))
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
if jump_mode == 'cat':
self.lin1 = Linear(num_layers * hidden, hidden)
else:
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def pool_complex(self, xs, data):
# All complexes have nodes so we can extract the batch size from cochains[0]
batch_size = data.cochains[0].batch.max() + 1
# The MP output is of shape [message_passing_dim, batch_size, feature_dim]
pooled_xs = torch.zeros(self.max_dim + 1, batch_size, xs[0].size(-1),
device=batch_size.device)
for i in range(len(xs)):
# It's very important that size is supplied.
pooled_xs[i, :, :] = self.pooling_fn(xs[i], data.cochains[i].batch, size=batch_size)
return pooled_xs
def jump_complex(self, jump_xs):
# Perform JumpingKnowledge at each level of the complex
xs = []
for jumpx in jump_xs:
xs += [self.jump(jumpx)]
return xs
def forward(self, data: ComplexBatch):
model_nonlinearity = get_nonlinearity(self.nonlinearity, return_module=False)
xs, jump_xs = None, None
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim)
xs = conv(*params)
data.set_xs(xs)
if self.jump_mode is not None:
if jump_xs is None:
jump_xs = [[] for _ in xs]
for i, x in enumerate(xs):
jump_xs[i] += [x]
if self.jump_mode is not None:
xs = self.jump_complex(jump_xs)
pooled_xs = self.pool_complex(xs, data)
x = pooled_xs.sum(dim=0)
x = model_nonlinearity(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
class SparseCIN(torch.nn.Module):
"""
A cellular version of GIN.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
dropout_rate: float = 0.5,
max_dim: int = 2, jump_mode=None, nonlinearity='relu', readout='sum',
train_eps=False, final_hidden_multiplier: int = 2, use_coboundaries=False,
readout_dims=(0, 1, 2), final_readout='sum', apply_dropout_before='lin2',
graph_norm='bn'):
super(SparseCIN, self).__init__()
self.max_dim = max_dim
if readout_dims is not None:
self.readout_dims = tuple([dim for dim in readout_dims if dim <= max_dim])
else:
self.readout_dims = list(range(max_dim+1))
self.final_readout = final_readout
self.dropout_rate = dropout_rate
self.apply_dropout_before = apply_dropout_before
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.pooling_fn = get_pooling_fn(readout)
self.graph_norm = get_graph_norm(graph_norm)
act_module = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
self.convs.append(
SparseCINConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None, passed_msg_up_nn=None,
passed_update_up_nn=None, passed_update_boundaries_nn=None,
train_eps=train_eps, max_dim=self.max_dim,
hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
self.lin1s = torch.nn.ModuleList()
for _ in range(max_dim + 1):
if jump_mode == 'cat':
# These layers don't use a bias. Then, in case a level is not present the output
# is just zero and it is not given by the biases.
self.lin1s.append(Linear(num_layers * hidden, final_hidden_multiplier * hidden,
bias=False))
else:
self.lin1s.append(Linear(hidden, final_hidden_multiplier * hidden))
self.lin2 = Linear(final_hidden_multiplier * hidden, num_classes)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.lin1s.reset_parameters()
self.lin2.reset_parameters()
def pool_complex(self, xs, data):
# All complexes have nodes so we can extract the batch size from cochains[0]
batch_size = data.cochains[0].batch.max() + 1
# print(batch_size)
# The MP output is of shape [message_passing_dim, batch_size, feature_dim]
pooled_xs = torch.zeros(self.max_dim + 1, batch_size, xs[0].size(-1),
device=batch_size.device)
for i in range(len(xs)):
# It's very important that size is supplied.
pooled_xs[i, :, :] = self.pooling_fn(xs[i], data.cochains[i].batch, size=batch_size)
new_xs = []
for i in range(self.max_dim + 1):
new_xs.append(pooled_xs[i])
return new_xs
def jump_complex(self, jump_xs):
# Perform JumpingKnowledge at each level of the complex
xs = []
for jumpx in jump_xs:
xs += [self.jump(jumpx)]
return xs
def forward(self, data: ComplexBatch, include_partial=False):
act = get_nonlinearity(self.nonlinearity, return_module=False)
xs, jump_xs = None, None
res = {}
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
start_to_process = 0
# if i == len(self.convs) - 2:
# start_to_process = 1
# if i == len(self.convs) - 1:
# start_to_process = 2
xs = conv(*params, start_to_process=start_to_process)
data.set_xs(xs)
if include_partial:
for k in range(len(xs)):
res[f"layer{c}_{k}"] = xs[k]
if self.jump_mode is not None:
if jump_xs is None:
jump_xs = [[] for _ in xs]
for i, x in enumerate(xs):
jump_xs[i] += [x]
if self.jump_mode is not None:
xs = self.jump_complex(jump_xs)
xs = self.pool_complex(xs, data)
# Select the dimensions we want at the end.
xs = [xs[i] for i in self.readout_dims]
if include_partial:
for k in range(len(xs)):
res[f"pool_{k}"] = xs[k]
new_xs = []
for i, x in enumerate(xs):
if self.apply_dropout_before == 'lin1':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
new_xs.append(act(self.lin1s[self.readout_dims[i]](x)))
x = torch.stack(new_xs, dim=0)
if self.apply_dropout_before == 'final_readout':
x = F.dropout(x, p=self.dropout_rate, training=self.training)
if self.final_readout == 'mean':
x = x.mean(0)
elif self.final_readout == 'sum':
x = x.sum(0)
else:
raise NotImplementedError
if self.apply_dropout_before not in ['lin1', 'final_readout']:
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
if include_partial:
res['out'] = x
return x, res
return x
def __repr__(self):
return self.__class__.__name__
class CINpp(SparseCIN):
"""CINpp
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
dropout_rate: float = 0.5, max_dim: int = 2, jump_mode=None,
nonlinearity='relu', readout='sum', train_eps=False,
final_hidden_multiplier: int = 2, use_coboundaries=False,
readout_dims=(0, 1, 2), final_readout='sum',
apply_dropout_before='lin2', graph_norm='bn'):
super(CINpp, self).__init__(num_input_features, num_classes, num_layers, hidden,
dropout_rate, max_dim, jump_mode, nonlinearity,
readout, train_eps, final_hidden_multiplier,
use_coboundaries, readout_dims, final_readout,
apply_dropout_before, graph_norm)
self.convs = torch.nn.ModuleList()
act_module = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
self.convs.append(
CINppConv(up_msg_size=layer_dim, down_msg_size=layer_dim,
boundary_msg_size=layer_dim, passed_msg_boundaries_nn=None, passed_msg_up_nn=None,
passed_msg_down_nn=None, passed_update_up_nn=None, passed_update_down_nn=None,
passed_update_boundaries_nn=None, train_eps=train_eps, max_dim=self.max_dim,
hidden=hidden, act_module=act_module, layer_dim=layer_dim,
graph_norm=self.graph_norm, use_coboundaries=use_coboundaries))
class EdgeCIN0(torch.nn.Module):
"""
A variant of CIN0 operating up to edge level. It may optionally ignore two_cell features.
This model is based on
https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
dropout_rate: float = 0.5,
jump_mode=None, nonlinearity='relu', include_top_features=True,
update_top_features=True,
readout='sum'):
super(EdgeCIN0, self).__init__()
self.max_dim = 1
self.include_top_features = include_top_features
# If the top features are included, then they can be updated by a network.
self.update_top_features = include_top_features and update_top_features
self.dropout_rate = dropout_rate
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.update_top_nns = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.pooling_fn = get_pooling_fn(readout)
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
v_conv_update = Sequential(
Linear(layer_dim, hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
conv_nonlinearity(),
BN(hidden))
e_conv_update = Sequential(
Linear(layer_dim, hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
conv_nonlinearity(),
BN(hidden))
v_conv_up = Sequential(
Linear(layer_dim * 2, layer_dim),
conv_nonlinearity(),
BN(layer_dim))
e_conv_down = Sequential(
Linear(layer_dim * 2, layer_dim),
conv_nonlinearity(),
BN(layer_dim))
e_conv_inp_dim = layer_dim * 2 if include_top_features else layer_dim
e_conv_up = Sequential(
Linear(e_conv_inp_dim, layer_dim),
conv_nonlinearity(),
BN(layer_dim))
self.convs.append(
EdgeCINConv(layer_dim, layer_dim, v_conv_up, e_conv_down, e_conv_up,
v_conv_update, e_conv_update, train_eps=False))
if self.update_top_features and i < num_layers - 1:
self.update_top_nns.append(Sequential(
Linear(layer_dim, hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
conv_nonlinearity(),
BN(hidden))
)
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
if jump_mode == 'cat':
self.lin1 = Linear(num_layers * hidden, hidden)
else:
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
for net in self.update_top_nns:
net.reset_parameters()
def pool_complex(self, xs, data):
# All complexes have nodes so we can extract the batch size from cochains[0]
batch_size = data.cochains[0].batch.max() + 1
# The MP output is of shape [message_passing_dim, batch_size, feature_dim]
pooled_xs = torch.zeros(self.max_dim + 1, batch_size, xs[0].size(-1),
device=batch_size.device)
for i in range(len(xs)):
# It's very important that size is supplied.
pooled_xs[i, :, :] = self.pooling_fn(xs[i], data.cochains[i].batch, size=batch_size)
return pooled_xs
def jump_complex(self, jump_xs):
# Perform JumpingKnowledge at each level of the complex
xs = []
for jumpx in jump_xs:
xs += [self.jump(jumpx)]
return xs
def forward(self, data: ComplexBatch):
model_nonlinearity = get_nonlinearity(self.nonlinearity, return_module=False)
xs, jump_xs = None, None
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params(max_dim=self.max_dim,
include_top_features=self.include_top_features)
xs = conv(*params)
# If we are at the last convolutional layer, we do not need to update after
# We also check two_cell features do indeed exist in this batch before doing this.
if self.update_top_features and c < len(self.convs) - 1 and 2 in data.cochains:
top_x = self.update_top_nns[c](data.cochains[2].x)
data.set_xs(xs + [top_x])
else:
data.set_xs(xs)
if self.jump_mode is not None:
if jump_xs is None:
jump_xs = [[] for _ in xs]
for i, x in enumerate(xs):
jump_xs[i] += [x]
if self.jump_mode is not None:
xs = self.jump_complex(jump_xs)
pooled_xs = self.pool_complex(xs, data)
x = pooled_xs.sum(dim=0)
x = model_nonlinearity(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
class Dummy(torch.nn.Module):
"""
A dummy cellular network model.
No parameters in the convolutional layers.
Readout at each layer is by summation.
Outputs are computed by one single linear layer.
"""
def __init__(self, num_input_features, num_classes, num_layers, max_dim: int = 2,
readout='sum'):
super(Dummy, self).__init__()
self.max_dim = max_dim
self.convs = torch.nn.ModuleList()
self.pooling_fn = get_pooling_fn(readout)
for i in range(num_layers):
self.convs.append(DummyCellularMessagePassing(max_dim=self.max_dim))
self.lin = Linear(num_input_features, num_classes)
def reset_parameters(self):
self.lin.reset_parameters()
def forward(self, data: ComplexBatch):
xs = None
for c, conv in enumerate(self.convs):
params = data.get_all_cochain_params()
xs = conv(*params)
data.set_xs(xs)
# All complexes have nodes so we can extract the batch size from cochains[0]
batch_size = data.cochains[0].batch.max() + 1
# The MP output is of shape [message_passing_dim, batch_size, feature_dim]
# We assume that all layers have the same feature size.
# Note that levels where we do MP at but where there was no data are set to 0.
# TODO: shall we retain the device as an attribute of self? then `device=batch_size.device`
# would become `device=self.device`
pooled_xs = torch.zeros(self.max_dim + 1, batch_size, xs[0].size(-1),
device=batch_size.device)
for i in range(len(xs)):
# It's very important that size is supplied.
# Otherwise, if we have complexes with no cells at certain levels, the wrong
# shape could be inferred automatically from data.cochains[i].batch.
# This makes sure the output tensor will have the right dimensions.
pooled_xs[i, :, :] = self.pooling_fn(xs[i], data.cochains[i].batch, size=batch_size)
# Reduce across the levels of the complexes
x = pooled_xs.sum(dim=0)
x = self.lin(x)
return x
def __repr__(self):
return self.__class__.__name__
class EdgeOrient(torch.nn.Module):
"""
A model for edge-defined signals taking edge orientation into account.
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
dropout_rate: float = 0.0, jump_mode=None, nonlinearity='id', readout='sum',
fully_invar=False):
super(EdgeOrient, self).__init__()
self.max_dim = 1
self.fully_invar = fully_invar
orient = not self.fully_invar
self.dropout_rate = dropout_rate
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.pooling_fn = get_pooling_fn(readout)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
# !!!!! Biases must be set to false. Otherwise, the model is not equivariant !!!!
update_up = Linear(layer_dim, hidden, bias=False)
update_down = Linear(layer_dim, hidden, bias=False)
update = Linear(layer_dim, hidden, bias=False)
self.convs.append(
OrientedConv(dim=1, up_msg_size=layer_dim, down_msg_size=layer_dim,
update_up_nn=update_up, update_down_nn=update_down, update_nn=update,
act_fn=get_nonlinearity(nonlinearity, return_module=False), orient=orient))
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data: CochainBatch, include_partial=False):
if self.fully_invar:
data.x = torch.abs(data.x)
for c, conv in enumerate(self.convs):
x = conv(data)
data.x = x
cell_pred = x
# To obtain orientation invariance, we take the absolute value of the features.
# Unless we did that already before the first layer.
batch_size = data.batch.max() + 1
if not self.fully_invar:
x = torch.abs(x)
x = self.pooling_fn(x, data.batch, size=batch_size)
# At this point we have invariance: we can use any non-linearity we like.
# Here, independently from previous non-linearities, we choose ReLU.
# Note that this makes the model non-linear even when employing identity
# in previous layers.
x = torch.relu(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
if include_partial:
return x, cell_pred
return x
def __repr__(self):
return self.__class__.__name__
class EdgeMPNN(torch.nn.Module):
"""
An MPNN operating in the line graph.
"""
def __init__(self, num_input_features, num_classes, num_layers, hidden,
dropout_rate: float = 0.0, jump_mode=None, nonlinearity='relu', readout='sum',
fully_invar=True):
super(EdgeMPNN, self).__init__()
self.max_dim = 1
self.dropout_rate = dropout_rate
self.fully_invar = fully_invar
orient = not self.fully_invar
self.jump_mode = jump_mode
self.convs = torch.nn.ModuleList()
self.nonlinearity = nonlinearity
self.pooling_fn = get_pooling_fn(readout)
for i in range(num_layers):
layer_dim = num_input_features if i == 0 else hidden
# We pass this lambda function to discard upper adjacencies
update_up = lambda x: 0
update_down = Linear(layer_dim, hidden, bias=False)
update = Linear(layer_dim, hidden, bias=False)
self.convs.append(
OrientedConv(dim=1, up_msg_size=layer_dim, down_msg_size=layer_dim,
update_up_nn=update_up, update_down_nn=update_down, update_nn=update,
act_fn=get_nonlinearity(nonlinearity, return_module=False), orient=orient))
self.jump = JumpingKnowledge(jump_mode) if jump_mode is not None else None
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
if self.jump_mode is not None:
self.jump.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data: CochainBatch, include_partial=False):
if self.fully_invar:
data.x = torch.abs(data.x)
for c, conv in enumerate(self.convs):
x = conv(data)
data.x = x
cell_pred = x
batch_size = data.batch.max() + 1
if not self.fully_invar:
x = torch.abs(x)
x = self.pooling_fn(x, data.batch, size=batch_size)
# At this point we have invariance: we can use any non-linearity we like.
# Here, independently from previous non-linearities, we choose ReLU.
# Note that this makes the model non-linear even when employing identity
# in previous layers.
x = torch.relu(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
if include_partial:
return x, cell_pred
return x
def __repr__(self):
return self.__class__.__name__
class MessagePassingAgnostic(torch.nn.Module):
"""
A model which does not perform any message passing.
Initial simplicial/cell representations are obtained by applying a dense layer, instead.
Sort of resembles a 'DeepSets'-likes architecture but on Simplicial/Cell Complexes.
"""
def __init__(self, num_input_features, num_classes, hidden, dropout_rate: float = 0.5,
max_dim: int = 2, nonlinearity='relu', readout='sum'):
super(MessagePassingAgnostic, self).__init__()
self.max_dim = max_dim
self.dropout_rate = dropout_rate
self.readout_type = readout
self.act = get_nonlinearity(nonlinearity, return_module=False)
self.lin0s = torch.nn.ModuleList()
for dim in range(max_dim + 1):
self.lin0s.append(Linear(num_input_features, hidden))
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
for lin0 in self.lin0s:
lin0.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data: ComplexBatch):
params = data.get_all_cochain_params(max_dim=self.max_dim, include_down_features=False)
xs = list()
for dim in range(len(params)):
x_dim = params[dim].x
x_dim = self.lin0s[dim](x_dim)
xs.append(self.act(x_dim))
pooled_xs = pool_complex(xs, data, self.max_dim, self.readout_type)
pooled_xs = self.act(self.lin1(pooled_xs))
x = pooled_xs.sum(dim=0)
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
| 27,151 | 40.015106 | 102 | py |
cwn | cwn-main/mp/__init__.py | 0 | 0 | 0 | py |
|
cwn | cwn-main/mp/test_orientation.py | import torch
import numpy as np
from data.datasets.flow import load_flow_dataset
from mp.models import EdgeOrient, EdgeMPNN
from mp.layers import OrientedConv
from data.complex import CochainBatch
from data.data_loading import DataLoader
from data.datasets.flow_utils import build_cochain
def generate_oriented_flow_pair():
# This is the complex from slide 19 of https://crisbodnar.github.io/files/mml_talk.pdf
B1 = np.array([
[-1, -1, 0, 0, 0, 0],
[+1, 0, -1, 0, 0, +1],
[ 0, +1, 0, -1, 0, -1],
[ 0, 0, +1, +1, -1, 0],
[ 0, 0, 0, 0, +1, 0],
])
B2 = np.array([
[-1, 0],
[+1, 0],
[ 0, +1],
[ 0, -1],
[ 0, 0],
[+1, +1],
])
x = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [-1.0]])
id = np.identity(x.shape[0])
T2 = np.diag([+1.0, +1.0, +1.0, +1.0, -1.0, -1.0])
cochain1 = build_cochain(B1, B2, id, x, 0)
cochain2 = build_cochain(B1, B2, T2, x, 0)
return cochain1, cochain2, torch.tensor(T2, dtype=torch.float)
def test_edge_orient_model_on_flow_dataset_with_batching():
dataset, _, _ = load_flow_dataset(num_points=100, num_train=20, num_test=2)
np.random.seed(4)
data_loader = DataLoader(dataset, batch_size=16)
model = EdgeOrient(num_input_features=1, num_classes=2, num_layers=2, hidden=5)
# We use the model in eval mode to test its inference behavior.
model.eval()
batched_preds = []
for batch in data_loader:
batched_pred = model.forward(batch)
batched_preds.append(batched_pred)
batched_preds = torch.cat(batched_preds, dim=0)
preds = []
for cochain in dataset:
pred = model.forward(CochainBatch.from_cochain_list([cochain]))
preds.append(pred)
preds = torch.cat(preds, dim=0)
assert (preds.size() == batched_preds.size())
assert torch.allclose(preds, batched_preds, atol=1e-5)
def test_edge_orient_conv_is_orientation_equivariant():
cochain1, cochain2, T2 = generate_oriented_flow_pair()
assert torch.equal(cochain1.lower_index, cochain2.lower_index)
assert torch.equal(cochain1.upper_index, cochain2.upper_index)
layer = OrientedConv(dim=1, up_msg_size=1, down_msg_size=1, update_up_nn=None,
update_down_nn=None, update_nn=None, act_fn=None)
out_up1, out_down1, _ = layer.propagate(cochain1.upper_index, cochain1.lower_index, None, x=cochain1.x,
up_attr=cochain1.upper_orient.view(-1, 1), down_attr=cochain1.lower_orient.view(-1, 1))
out_up2, out_down2, _ = layer.propagate(cochain2.upper_index, cochain2.lower_index, None, x=cochain2.x,
up_attr=cochain2.upper_orient.view(-1, 1), down_attr=cochain2.lower_orient.view(-1, 1))
assert torch.equal(T2 @ out_up1, out_up2)
assert torch.equal(T2 @ out_down1, out_down2)
assert torch.equal(T2 @ (cochain1.x + out_up1 + out_down1), cochain2.x + out_up2 + out_down2)
def test_edge_orient_model_with_tanh_is_orientation_equivariant_and_invariant_at_readout():
cochain1, cochain2, T2 = generate_oriented_flow_pair()
assert torch.equal(cochain1.lower_index, cochain2.lower_index)
assert torch.equal(cochain1.upper_index, cochain2.upper_index)
model = EdgeOrient(num_input_features=1, num_classes=2, num_layers=2, hidden=5,
nonlinearity='tanh', dropout_rate=0.0)
model.eval()
final1, pred1 = model.forward(CochainBatch.from_cochain_list([cochain1]), include_partial=True)
final2, pred2 = model.forward(CochainBatch.from_cochain_list([cochain2]), include_partial=True)
# Check equivariant.
assert torch.equal(T2 @ pred1, pred2)
# Check invariant after readout.
assert torch.equal(final1, final2)
def test_edge_orient_model_with_id_is_orientation_equivariant_and_invariant_at_readout():
cochain1, cochain2, T2 = generate_oriented_flow_pair()
assert torch.equal(cochain1.lower_index, cochain2.lower_index)
assert torch.equal(cochain1.upper_index, cochain2.upper_index)
model = EdgeOrient(num_input_features=1, num_classes=2, num_layers=2, hidden=5,
nonlinearity='id', dropout_rate=0.0)
model.eval()
final1, pred1 = model.forward(CochainBatch.from_cochain_list([cochain1]), include_partial=True)
final2, pred2 = model.forward(CochainBatch.from_cochain_list([cochain2]), include_partial=True)
# Check equivariant.
assert torch.equal(T2 @ pred1, pred2)
# Check invariant after readout.
assert torch.equal(final1, final2)
def test_edge_orient_model_with_relu_is_not_orientation_equivariant_or_invariant():
cochain1, cochain2, T2 = generate_oriented_flow_pair()
assert torch.equal(cochain1.lower_index, cochain2.lower_index)
assert torch.equal(cochain1.upper_index, cochain2.upper_index)
model = EdgeOrient(num_input_features=1, num_classes=2, num_layers=2, hidden=5,
nonlinearity='relu', dropout_rate=0.0)
model.eval()
_, pred1 = model.forward(CochainBatch.from_cochain_list([cochain1]), include_partial=True)
_, pred2 = model.forward(CochainBatch.from_cochain_list([cochain2]), include_partial=True)
# Check not equivariant.
assert not torch.equal(T2 @ pred1, pred2)
# Check not invariant.
assert not torch.equal(pred1, pred2)
def test_edge_mpnn_model_is_orientation_invariant():
cochain1, cochain2, T2 = generate_oriented_flow_pair()
assert torch.equal(cochain1.lower_index, cochain2.lower_index)
assert torch.equal(cochain1.upper_index, cochain2.upper_index)
model = EdgeMPNN(num_input_features=1, num_classes=2, num_layers=2, hidden=5,
nonlinearity='id', dropout_rate=0.0)
model.eval()
_, pred1 = model.forward(CochainBatch.from_cochain_list([cochain1]), include_partial=True)
_, pred2 = model.forward(CochainBatch.from_cochain_list([cochain2]), include_partial=True)
# Check the model is orientation invariant.
assert torch.equal(pred1, pred2)
| 5,926 | 39.047297 | 107 | py |
cwn | cwn-main/mp/graph_models.py | """
Code based on https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
Copyright (c) 2020 Matthias Fey <[email protected]>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import torch
import torch.nn.functional as F
from torch.nn import Linear, Sequential, BatchNorm1d as BN
from torch_geometric.nn import GINConv, JumpingKnowledge
from mp.nn import get_nonlinearity, get_pooling_fn
class GIN0(torch.nn.Module):
def __init__(self, num_features, num_layers, hidden, num_classes, readout='sum',
dropout_rate=0.5, nonlinearity='relu'):
super(GIN0, self).__init__()
self.pooling_fn = get_pooling_fn(readout)
self.nonlinearity = nonlinearity
self.dropout_rate = dropout_rate
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
self.conv1 = GINConv(
Sequential(
Linear(num_features, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=False)
self.convs = torch.nn.ModuleList()
for i in range(num_layers - 1):
self.convs.append(
GINConv(
Sequential(
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=False))
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
self.conv1.reset_parameters()
for conv in self.convs:
conv.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data):
model_nonlinearity = get_nonlinearity(self.nonlinearity, return_module=False)
x, edge_index, batch = data.x, data.edge_index, data.batch
x = self.conv1(x, edge_index)
for conv in self.convs:
x = conv(x, edge_index)
x = self.pooling_fn(x, batch)
x = model_nonlinearity(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
class GIN0WithJK(torch.nn.Module):
def __init__(self, num_features, num_layers, hidden, num_classes, mode='cat', readout='sum',
dropout_rate=0.5, nonlinearity='relu'):
super(GIN0WithJK, self).__init__()
self.pooling_fn = get_pooling_fn(readout)
self.dropout_rate = dropout_rate
self.nonlinearity = nonlinearity
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
self.conv1 = GINConv(
Sequential(
Linear(num_features, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=False)
self.convs = torch.nn.ModuleList()
for i in range(num_layers - 1):
self.convs.append(
GINConv(
Sequential(
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=False))
self.jump = JumpingKnowledge(mode)
if mode == 'cat':
self.lin1 = Linear(num_layers * hidden, hidden)
else:
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
self.conv1.reset_parameters()
for conv in self.convs:
conv.reset_parameters()
self.jump.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data):
model_nonlinearity = get_nonlinearity(self.nonlinearity, return_module=False)
x, edge_index, batch = data.x, data.edge_index, data.batch
x = self.conv1(x, edge_index)
xs = [x]
for conv in self.convs:
x = conv(x, edge_index)
xs += [x]
x = self.jump(xs)
x = self.pooling_fn(x, batch)
x = model_nonlinearity(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
class GIN(torch.nn.Module):
def __init__(self, num_features, num_layers, hidden, num_classes, readout='sum',
dropout_rate=0.5, nonlinearity='relu'):
super(GIN, self).__init__()
self.pooling_fn = get_pooling_fn(readout)
self.dropout_rate = dropout_rate
self.nonlinearity = nonlinearity
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
self.conv1 = GINConv(
Sequential(
Linear(num_features, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=True)
self.convs = torch.nn.ModuleList()
for i in range(num_layers - 1):
self.convs.append(
GINConv(
Sequential(
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=True))
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
self.conv1.reset_parameters()
for conv in self.convs:
conv.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data):
model_nonlinearity = get_nonlinearity(self.nonlinearity, return_module=False)
x, edge_index, batch = data.x, data.edge_index, data.batch
x = self.conv1(x, edge_index)
for conv in self.convs:
x = conv(x, edge_index)
x = self.pooling_fn(x, batch)
x = model_nonlinearity(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
class GINWithJK(torch.nn.Module):
def __init__(self, num_features, num_layers, hidden, num_classes, mode='cat', readout='sum',
dropout_rate=0.5, nonlinearity='relu'):
super(GINWithJK, self).__init__()
self.pooling_fn = get_pooling_fn(readout)
self.dropout_rate = dropout_rate
self.nonlinearity = nonlinearity
conv_nonlinearity = get_nonlinearity(nonlinearity, return_module=True)
self.conv1 = GINConv(
Sequential(
Linear(num_features, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=True)
self.convs = torch.nn.ModuleList()
for i in range(num_layers - 1):
self.convs.append(
GINConv(
Sequential(
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
Linear(hidden, hidden),
BN(hidden),
conv_nonlinearity(),
), train_eps=True))
self.jump = JumpingKnowledge(mode)
if mode == 'cat':
self.lin1 = Linear(num_layers * hidden, hidden)
else:
self.lin1 = Linear(hidden, hidden)
self.lin2 = Linear(hidden, num_classes)
def reset_parameters(self):
self.conv1.reset_parameters()
for conv in self.convs:
conv.reset_parameters()
self.jump.reset_parameters()
self.lin1.reset_parameters()
self.lin2.reset_parameters()
def forward(self, data):
model_nonlinearity = get_nonlinearity(self.nonlinearity, return_module=False)
x, edge_index, batch = data.x, data.edge_index, data.batch
x = self.conv1(x, edge_index)
xs = [x]
for conv in self.convs:
x = conv(x, edge_index)
xs += [x]
x = self.jump(xs)
x = self.pooling_fn(x, batch)
x = model_nonlinearity(self.lin1(x))
x = F.dropout(x, p=self.dropout_rate, training=self.training)
x = self.lin2(x)
return x
def __repr__(self):
return self.__class__.__name__
| 10,168 | 37.086142 | 96 | py |
cwn | cwn-main/mp/test_molec_models.py | import torch
import itertools
import pytest
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from mp.molec_models import EmbedSparseCIN, OGBEmbedSparseCIN, EmbedSparseCINNoRings, EmbedGIN
from data.data_loading import DataLoader, load_dataset
def test_zinc_sparse_cin0_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2]
bs = list(range(2, len(data_list)+1))
params = itertools.product(bs, dims, dims)
torch.manual_seed(0)
for batch_size, batch_max_dim, model_max_dim in params:
if batch_max_dim > model_max_dim:
continue
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
model = EmbedSparseCIN(atom_types=32, bond_types=4, out_size=3, num_layers=3, hidden=5,
jump_mode='cat', max_dim=model_max_dim)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_res = {}
for batch in data_loader:
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
batched_pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in batched_res:
batched_res[key] = []
batched_res[key].append(res[key])
for key in batched_res:
batched_res[key] = torch.cat(batched_res[key], dim=0)
unbatched_res = {}
for complex in data_list:
batch = ComplexBatch.from_complex_list([complex], max_dim=batch_max_dim)
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in unbatched_res:
unbatched_res[key] = []
unbatched_res[key].append(res[key])
for key in unbatched_res:
unbatched_res[key] = torch.cat(unbatched_res[key], dim=0)
for key in set(list(unbatched_res.keys()) + list(batched_res.keys())):
assert torch.allclose(unbatched_res[key], batched_res[key], atol=1e-6), (
print(key, torch.max(torch.abs(unbatched_res[key] - batched_res[key]))))
def test_embed_sparse_cin_no_rings_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1]
bs = list(range(2, len(data_list)+1))
params = itertools.product(bs, dims, dims)
torch.manual_seed(0)
for batch_size, batch_max_dim, model_max_dim in params:
if batch_max_dim > model_max_dim:
continue
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
model = EmbedSparseCINNoRings(atom_types=32, bond_types=4, out_size=3, num_layers=3, hidden=5)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_res = []
for batch in data_loader:
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
batched_pred = model.forward(batch)
batched_res.append(batched_pred)
batched_res = torch.cat(batched_res, dim=0)
unbatched_res = []
for complex in data_list:
batch = ComplexBatch.from_complex_list([complex], max_dim=batch_max_dim)
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
pred = model.forward(batch)
unbatched_res.append(pred)
unbatched_res = torch.cat(unbatched_res, dim=0)
assert torch.allclose(unbatched_res, batched_res, atol=1e-6)
def test_embed_gin_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1]
bs = list(range(2, len(data_list)+1))
params = itertools.product(bs, dims, dims)
torch.manual_seed(0)
for batch_size, batch_max_dim, model_max_dim in params:
if batch_max_dim > model_max_dim:
continue
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
model = EmbedGIN(atom_types=32, bond_types=4, out_size=3, num_layers=3, hidden=5)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_res = []
for batch in data_loader:
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
batched_pred = model.forward(batch)
batched_res.append(batched_pred)
batched_res = torch.cat(batched_res, dim=0)
unbatched_res = []
for complex in data_list:
batch = ComplexBatch.from_complex_list([complex], max_dim=batch_max_dim)
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
pred = model.forward(batch)
unbatched_res.append(pred)
unbatched_res = torch.cat(unbatched_res, dim=0)
assert torch.allclose(unbatched_res, batched_res, atol=1e-6)
@pytest.mark.data
def test_zinc_sparse_cin0_model_with_batching_on_proteins():
"""Check this runs without errors and that batching and no batching produce the same output."""
dataset = load_dataset('PROTEINS', max_dim=2, fold=0, init_method='mean')
assert len(dataset) == 1113
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
max_dim = 2
torch.manual_seed(0)
data_loader = DataLoader(dataset, batch_size=32, max_dim=max_dim)
model = EmbedSparseCIN(atom_types=64, bond_types=4, out_size=3, num_layers=3, hidden=5,
jump_mode='cat', max_dim=max_dim)
model.eval()
batched_res = {}
for batch in data_loader:
# Simulate no edge and two_cell features to test init layer
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
# ZincSparseCIN assumes features are unidimensional like in ZINC
batch.cochains[0].x = batch.cochains[0].x[:, :1]
batched_pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in batched_res:
batched_res[key] = []
batched_res[key].append(res[key])
for key in batched_res:
batched_res[key] = torch.cat(batched_res[key], dim=0)
unbatched_res = {}
for complex in dataset:
batch = ComplexBatch.from_complex_list([complex], max_dim=max_dim)
# Simulate no edge and two_cell features to test init layer
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
# ZincSparseCIN assumes features are unidimensional like in ZINC
batch.cochains[0].x = batch.cochains[0].x[:, :1]
pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in unbatched_res:
unbatched_res[key] = []
unbatched_res[key].append(res[key])
for key in unbatched_res:
unbatched_res[key] = torch.cat(unbatched_res[key], dim=0)
for key in set(list(unbatched_res.keys()) + list(batched_res.keys())):
assert torch.allclose(unbatched_res[key], batched_res[key], atol=1e-6), (
print(key, torch.max(torch.abs(unbatched_res[key] - batched_res[key]))))
def test_ogb_sparse_cin0_model_with_batching():
"""Check this runs without errors and that batching and no batching produce the same output."""
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2]
bs = list(range(2, len(data_list)+1))
params = itertools.product(bs, dims, dims)
torch.manual_seed(0)
for batch_size, batch_max_dim, model_max_dim in params:
if batch_max_dim > model_max_dim:
continue
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
model = OGBEmbedSparseCIN(out_size=3, num_layers=3, hidden=5,
jump_mode=None, max_dim=model_max_dim)
# We use the model in eval mode to avoid problems with batch norm.
model.eval()
batched_res = {}
for batch in data_loader:
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
batched_pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in batched_res:
batched_res[key] = []
batched_res[key].append(res[key])
for key in batched_res:
batched_res[key] = torch.cat(batched_res[key], dim=0)
unbatched_res = {}
for complex in data_list:
batch = ComplexBatch.from_complex_list([complex], max_dim=batch_max_dim)
# Simulate no edge and two_cell features to test init layer
if len(batch.cochains) >= 2:
batch.cochains[1].x = None
if len(batch.cochains) == 3:
batch.cochains[2].x = None
pred, res = model.forward(batch, include_partial=True)
for key in res:
if key not in unbatched_res:
unbatched_res[key] = []
unbatched_res[key].append(res[key])
for key in unbatched_res:
unbatched_res[key] = torch.cat(unbatched_res[key], dim=0)
for key in set(list(unbatched_res.keys()) + list(batched_res.keys())):
assert torch.allclose(unbatched_res[key], batched_res[key], atol=1e-6), (
print(key, torch.max(torch.abs(unbatched_res[key] - batched_res[key]))))
| 11,149 | 38.122807 | 102 | py |
cwn | cwn-main/mp/test_cell_mp.py | import pytest
import torch
from data.helper_test import check_edge_index_are_the_same, check_edge_attr_are_the_same
from mp.cell_mp import CochainMessagePassing
from torch_geometric.nn.conv import MessagePassing
from data.dummy_complexes import (get_square_dot_complex, get_house_complex,
get_colon_complex, get_fullstop_complex,
get_bridged_complex, convert_to_graph)
from data.utils import compute_ring_2complex
def test_edge_propagate_in_cmp():
"""We build a graph in the shape of a house (a triangle on top of a square)
and test propagation at the edge level."""
house_complex = get_house_complex()
e = house_complex.get_cochain_params(dim=1)
assert e.kwargs['boundary_index'] is not None, e.kwargs['boundary_index']
# Extract the message passing object and propagate
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, down_msg, boundary_msg = cmp.propagate(e.up_index, e.down_index,
e.boundary_index, x=e.x,
up_attr=e.kwargs['up_attr'],
down_attr=e.kwargs['down_attr'],
boundary_attr=e.kwargs['boundary_attr'])
expected_down_msg = torch.tensor([[6], [10], [17], [9], [13], [10]], dtype=torch.float)
assert torch.equal(down_msg, expected_down_msg)
expected_up_msg = torch.tensor([[0], [0], [11], [0], [9], [8]], dtype=torch.float)
assert torch.equal(up_msg, expected_up_msg)
expected_boundary_msg = torch.tensor([[3], [5], [7], [5], [9], [8]], dtype=torch.float)
assert torch.equal(boundary_msg, expected_boundary_msg)
def test_propagate_at_vertex_level_in_cmp():
"""We build a graph in the shape of a house (a triangle on top of a square)
and test propagation at the vertex level. This makes sure propagate works when
down_index is None.
"""
house_complex = get_house_complex()
v = house_complex.get_cochain_params(dim=0)
# Extract the message passing object and propagate
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, down_msg, boundary_msg = cmp.propagate(v.up_index, v.down_index,
v.boundary_index, x=v.x,
up_attr=v.kwargs['up_attr'],
down_attr=v.kwargs['down_attr'],
boundary_attr=v.kwargs['boundary_attr'])
expected_up_msg = torch.tensor([[6], [4], [11], [9], [7]], dtype=torch.float)
assert torch.equal(up_msg, expected_up_msg)
expected_down_msg = torch.zeros(5, 1)
assert torch.equal(down_msg, expected_down_msg)
expected_boundary_msg = torch.zeros(5, 1)
assert torch.equal(boundary_msg, expected_boundary_msg)
def test_propagate_at_two_cell_level_in_cmp_when_there_is_a_single_one():
"""We build a graph in the shape of a house (a triangle on top of a square)
and test propagation at the two_cell level. This makes sure that propagate works when
up_index is None."""
house_complex = get_house_complex()
t = house_complex.get_cochain_params(dim=2)
# Extract the message passing object and propagate
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, down_msg, boundary_msg = cmp.propagate(t.up_index, t.down_index,
t.boundary_index, x=t.x,
up_attr=t.kwargs['up_attr'],
down_attr=t.kwargs['down_attr'],
boundary_attr=t.kwargs['boundary_attr'])
expected_up_msg = torch.zeros(1, 1)
assert torch.equal(up_msg, expected_up_msg)
expected_down_msg = torch.zeros(1, 1)
assert torch.equal(down_msg, expected_down_msg)
expected_boundary_msg = torch.tensor([[14]], dtype=torch.float)
assert torch.equal(boundary_msg, expected_boundary_msg)
def test_propagate_at_two_cell_level_in_cmp():
"""We build a graph formed of two triangles sharing an edge.
This makes sure that propagate works when up_index is None."""
# TODO: Refactor this test to use the kite complex
# When there is a single two_cell, there is no upper or lower adjacency
up_index = None
down_index = torch.tensor([[0, 1],
[1, 0]], dtype=torch.long)
# Add features for the edges shared by the triangles
down_attr = torch.tensor([[1], [1]])
# We initialise the vertices with dummy scalar features
x = torch.tensor([[32], [17]], dtype=torch.float)
# Extract the message passing object and propagate
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, down_msg, _ = cmp.propagate(up_index, down_index, None, x=x, down_attr=down_attr)
expected_updated_x = torch.tensor([[17], [32]], dtype=torch.float)
assert torch.equal(up_msg + down_msg, expected_updated_x)
def test_smp_messaging_with_isolated_nodes():
"""
This checks how pyG handles messages for isolated nodes. This shows that it sends a zero vector.
"""
square_dot_complex = get_square_dot_complex()
params = square_dot_complex.get_cochain_params(dim=0)
mp = MessagePassing()
out = mp.propagate(edge_index=params.up_index, x=params.x)
isolated_out = out[4]
# This confirms pyG returns a zero message to isolated vertices
assert torch.equal(isolated_out, torch.zeros_like(isolated_out))
for i in range(4):
assert not torch.equal(out[i], torch.zeros_like(out[i]))
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, down_msg, _ = cmp.propagate(up_index=params.up_index, down_index=None, boundary_index=None,
x=params.x, up_attr=None)
assert torch.equal(out, up_msg)
assert torch.equal(down_msg, torch.zeros_like(down_msg))
def test_cmp_messaging_with_isolated_node_only():
"""
This checks how pyG handles messages for one isolated node.
"""
fullstop_complex = get_fullstop_complex()
params = fullstop_complex.get_cochain_params(dim=0)
empty_edge_index = torch.LongTensor([[],[]])
mp = MessagePassing()
mp_out = mp.propagate(edge_index=empty_edge_index, x=params.x)
# This confirms pyG returns a zero message when edge_index is empty
assert torch.equal(mp_out, torch.zeros_like(mp_out))
# This confirms behavior is consistent with our framework
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, _, _ = cmp.propagate(up_index=params.up_index, down_index=None, boundary_index=None,
x=params.x, up_attr=None)
assert torch.equal(mp_out, up_msg)
def test_cmp_messaging_with_two_isolated_nodes_only():
"""
This checks how pyG handles messages for two isolated nodes.
"""
colon_complex = get_colon_complex()
params = colon_complex.get_cochain_params(dim=0)
empty_edge_index = torch.LongTensor([[],[]])
mp = MessagePassing()
mp_out = mp.propagate(edge_index=empty_edge_index, x=params.x)
# This confirms pyG returns a zero message when edge_index is empty
assert torch.equal(mp_out, torch.zeros_like(mp_out))
# This confirms behavior is consistent with our framework
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
up_msg, _, _ = cmp.propagate(up_index=params.up_index, down_index=None, boundary_index=None,
x=params.x, up_attr=None)
assert torch.equal(mp_out, up_msg)
def test_cmp_messaging_with_replicated_adjs():
"""
This checks message passing works as expected in case cells/simplices
share more than one (co)boundary.
"""
bridged_complex = get_bridged_complex()
bridged_graph = convert_to_graph(bridged_complex)
bridged_complex_from_graph = compute_ring_2complex(
bridged_graph.x, bridged_graph.edge_index, bridged_graph.edge_attr, bridged_graph.num_nodes,
bridged_graph.y, init_method='sum', init_edges=True, init_rings=True)
check_edge_index_are_the_same(bridged_complex_from_graph.edges.upper_index, bridged_complex.edges.upper_index)
check_edge_index_are_the_same(bridged_complex_from_graph.two_cells.lower_index, bridged_complex.two_cells.lower_index)
check_edge_attr_are_the_same(bridged_complex.cochains[1].boundary_index, bridged_complex.cochains[1].x, bridged_graph.edge_index, bridged_graph.edge_attr)
check_edge_attr_are_the_same(bridged_complex_from_graph.cochains[1].boundary_index, bridged_complex_from_graph.cochains[1].x, bridged_graph.edge_index, bridged_graph.edge_attr)
# verify up-messaging with multiple shared coboundaries
e = bridged_complex.get_cochain_params(dim=1)
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
e_up_msg, e_down_msg, e_boundary_msg = cmp.propagate(e.up_index, e.down_index,
e.boundary_index, x=e.x,
up_attr=e.kwargs['up_attr'],
down_attr=e.kwargs['down_attr'],
boundary_attr=e.kwargs['boundary_attr'])
expected_e_up_msg = torch.tensor([[4+5+6+2+3+4], # edge 0
[3+5+6+1+3+4], # edge 1
[2+5+6+1+2+4], # edge 2
[1+5+6+1+2+3], # edge 3
[1+4+6+2+3+6], # edge 4
[1+4+5+2+3+5]], # edge 5
dtype=torch.float)
assert torch.equal(e_up_msg, expected_e_up_msg)
# same but start from graph instead
e = bridged_complex_from_graph.get_cochain_params(dim=1)
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
e_up_msg, e_down_msg, e_boundary_msg = cmp.propagate(e.up_index, e.down_index,
e.boundary_index, x=e.x,
up_attr=e.kwargs['up_attr'],
down_attr=e.kwargs['down_attr'],
boundary_attr=e.kwargs['boundary_attr'])
expected_e_up_msg = torch.tensor([[4+5+6+2+3+4], # edge 0-1 (0)
[1+5+6+1+2+3], # edge 0-3 (3)
[3+5+6+1+3+4], # edge 1-2 (1)
[1+4+5+2+3+5], # edge 1-4 (5)
[2+5+6+1+2+4], # edge 2-3 (2)
[1+4+6+2+3+6]], # edge 3-4 (4)
dtype=torch.float)
assert torch.equal(e_up_msg, expected_e_up_msg)
# verify down-messaging with multiple shared boundaries
t = bridged_complex.get_cochain_params(dim=2)
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
t_up_msg, t_down_msg, t_boundary_msg = cmp.propagate(t.up_index, t.down_index,
t.boundary_index, x=t.x,
up_attr=t.kwargs['up_attr'],
down_attr=t.kwargs['down_attr'],
boundary_attr=t.kwargs['boundary_attr'])
expected_t_down_msg = torch.tensor([[2+2+3+3], # ring 0
[1+1+3+3], # ring 1
[1+1+2+2]], # ring 2
dtype=torch.float)
assert torch.equal(t_down_msg, expected_t_down_msg)
expected_t_boundary_msg = torch.tensor([[1+6+5+4], # ring 0
[2+3+5+6], # ring 1
[1+2+3+4]], # ring 2
dtype=torch.float)
assert torch.equal(t_boundary_msg, expected_t_boundary_msg)
# same but start from graph instead
t = bridged_complex_from_graph.get_cochain_params(dim=2)
cmp = CochainMessagePassing(up_msg_size=1, down_msg_size=1)
t_up_msg, t_down_msg, t_boundary_msg = cmp.propagate(t.up_index, t.down_index,
t.boundary_index, x=t.x,
up_attr=t.kwargs['up_attr'],
down_attr=t.kwargs['down_attr'],
boundary_attr=t.kwargs['boundary_attr'])
t0_x = 1+2+4+5 # 12
t1_x = 2+3+4+5 # 14
t2_x = 1+2+3+4 # 10
expected_t_down_msg = torch.tensor([[t1_x + t1_x + t2_x + t2_x], # ring 0-1-4-3 (0)
[t0_x + t0_x + t1_x + t1_x], # ring 0-1-2-3 (2)
[t0_x + t0_x + t2_x + t2_x]], # ring 1-2-3-4 (1)
dtype=torch.float)
assert torch.equal(t_down_msg, expected_t_down_msg)
expected_t_boundary_msg = torch.tensor([[1+6+5+4], # ring 0
[1+2+3+4], # ring 2
[2+3+5+6]], # ring 1
dtype=torch.float)
assert torch.equal(t_boundary_msg, expected_t_boundary_msg) | 13,576 | 49.285185 | 180 | py |
cwn | cwn-main/data/test_dataset.py | import pytest
import os
from data.data_loading import load_graph_dataset
from data.datasets import TUDataset, DummyMolecularDataset, DummyDataset
from data.utils import compute_clique_complex_with_gudhi, compute_ring_2complex
from data.helper_test import compare_complexes, compare_complexes_without_2feats
from definitions import ROOT_DIR
def validate_data_retrieval(dataset, graph_list, exp_dim, include_down_adj, ring_size=None):
assert len(dataset) == len(graph_list)
for i in range(len(graph_list)):
graph = graph_list[i]
yielded = dataset[i]
if ring_size is not None:
expected = compute_ring_2complex(graph.x, graph.edge_index, None,
graph.num_nodes, y=graph.y,
max_k=ring_size, include_down_adj=include_down_adj,
init_rings=True)
else:
expected = compute_clique_complex_with_gudhi(graph.x, graph.edge_index,
graph.num_nodes, expansion_dim=exp_dim,
y=graph.y, include_down_adj=include_down_adj)
compare_complexes(yielded, expected, include_down_adj)
@pytest.mark.data
def test_data_retrieval_on_proteins():
dataset = TUDataset(os.path.join(ROOT_DIR, 'datasets', 'PROTEINS'), 'PROTEINS', max_dim=3,
num_classes=2, fold=0, degree_as_tag=False, init_method='sum', include_down_adj=True)
graph_list, train_ids, val_ids, _, num_classes = load_graph_dataset('PROTEINS', fold=0)
assert dataset.include_down_adj
assert dataset.num_classes == num_classes
validate_data_retrieval(dataset, graph_list, 3, True)
validate_data_retrieval(dataset[train_ids], [graph_list[i] for i in train_ids], 3, True)
validate_data_retrieval(dataset[val_ids], [graph_list[i] for i in val_ids], 3, True)
return
@pytest.mark.data
def test_data_retrieval_on_proteins_with_rings():
dataset = TUDataset(os.path.join(ROOT_DIR, 'datasets', 'PROTEINS'), 'PROTEINS', max_dim=2,
num_classes=2, fold=0, degree_as_tag=False, init_method='sum', include_down_adj=True,
max_ring_size=6)
graph_list, train_ids, val_ids, _, num_classes = load_graph_dataset('PROTEINS', fold=0)
assert dataset.include_down_adj
assert dataset.num_classes == num_classes
# Reducing to val_ids only, to save some time. Uncomment the lines below to test on the whole set
# validate_data_retrieval(dataset, graph_list, 2, True, 6)
# validate_data_retrieval(dataset[train_ids], [graph_list[i] for i in train_ids], 2, True, 6)
validate_data_retrieval(dataset[val_ids], [graph_list[i] for i in val_ids], 2, True, 6)
def test_dummy_dataset_data_retrieval():
complexes = DummyDataset.factory()
dataset = DummyDataset(os.path.join(ROOT_DIR, 'datasets', 'DUMMY'))
assert len(complexes) == len(dataset)
for i in range(len(dataset)):
compare_complexes(dataset[i], complexes[i], True)
def test_dummy_mol_dataset_data_retrieval():
complexes = DummyMolecularDataset.factory(False)
dataset = DummyMolecularDataset(os.path.join(ROOT_DIR, 'datasets', 'DUMMYM'), False)
assert len(complexes) == len(dataset)
for i in range(len(dataset)):
compare_complexes(dataset[i], complexes[i], True)
def test_dummy_mol_dataset_data_retrieval_without_2feats():
complexes = DummyMolecularDataset.factory(True)
dataset = DummyMolecularDataset(os.path.join(ROOT_DIR, 'datasets', 'DUMMYM'), True)
assert len(complexes) == len(dataset)
for i in range(len(dataset)):
compare_complexes_without_2feats(dataset[i], complexes[i], True)
| 3,813 | 46.08642 | 109 | py |
cwn | cwn-main/data/perm_utils.py | import torch
import numpy as np
from scipy import sparse as sp
from torch_geometric.data import Data
def permute_graph(graph: Data, P: np.ndarray) -> Data:
# TODO: support edge features and their permutation
assert graph.edge_attr is None
# Check validity of permutation matrix
n = graph.x.size(0)
if not is_valid_permutation_matrix(P, n):
raise AssertionError
# Apply permutation to features
x = graph.x.numpy()
x_perm = torch.FloatTensor(P @ x)
# Apply perm to labels, if per-node
if graph.y is None:
y_perm = None
elif graph.y.size(0) == n:
y = graph.y.numpy()
y_perm = torch.tensor(P @ y)
else:
y_perm = graph.y.clone().detach()
# Apply permutation to adjacencies, if any
if graph.edge_index.size(1) > 0:
inps = (np.ones(graph.edge_index.size(1)), (graph.edge_index[0].numpy(), graph.edge_index[1].numpy()))
A = sp.csr_matrix(inps, shape=(n,n))
P = sp.csr_matrix(P)
A_perm = P.dot(A).dot(P.transpose()).tocoo()
edge_index_perm = torch.LongTensor(np.vstack((A_perm.row, A_perm.col)))
else:
edge_index_perm = graph.edge_index.clone().detach()
# Instantiate new graph
graph_perm = Data(x=x_perm, edge_index=edge_index_perm, y=y_perm)
return graph_perm
def is_valid_permutation_matrix(P: np.ndarray, n: int):
valid = True
valid &= P.ndim == 2
valid &= P.shape[0] == n
valid &= np.all(P.sum(0) == np.ones(n))
valid &= np.all(P.sum(1) == np.ones(n))
valid &= np.all(P.max(0) == np.ones(n))
valid &= np.all(P.max(1) == np.ones(n))
if n > 1:
valid &= np.all(P.min(0) == np.zeros(n))
valid &= np.all(P.min(1) == np.zeros(n))
valid &= not np.array_equal(P, np.eye(n))
return valid
def generate_permutation_matrices(size, amount=10, seed=43):
Ps = list()
random_state = np.random.RandomState(seed)
count = 0
while count < amount:
I = np.eye(size)
perm = random_state.permutation(size)
P = I[perm]
if is_valid_permutation_matrix(P, size):
Ps.append(P)
count += 1
return Ps | 2,177 | 29.25 | 110 | py |
cwn | cwn-main/data/test_data.py | import torch
from data.dummy_complexes import get_house_complex
def test_up_and_down_feature_extraction_on_house_complex():
house_complex = get_house_complex()
v_cochain_params = house_complex.get_cochain_params(dim=0)
v_up_attr = v_cochain_params.kwargs['up_attr']
expected_v_up_attr = torch.tensor([[1], [1], [4], [4], [2], [2], [3], [3], [6], [6], [5], [5]],
dtype=torch.float)
assert torch.equal(expected_v_up_attr, v_up_attr)
e_cochain_params = house_complex.get_cochain_params(dim=1)
e_up_attr = e_cochain_params.kwargs['up_attr']
expected_e_up_attr = torch.tensor([[1], [1], [1], [1], [1], [1]], dtype=torch.float)
assert torch.equal(expected_e_up_attr, e_up_attr)
e_down_attr = e_cochain_params.kwargs['down_attr']
expected_e_down_attr = torch.tensor([[2], [2], [1], [1], [3], [3], [3], [3], [4], [4], [4], [4],
[3], [3], [4], [4], [5], [5]], dtype=torch.float)
assert torch.equal(expected_e_down_attr, e_down_attr)
t_cochain_params = house_complex.get_cochain_params(dim=2)
t_up_attr = t_cochain_params.kwargs['up_attr']
assert t_up_attr is None
t_down_attr = t_cochain_params.kwargs['down_attr']
assert t_down_attr is None
def test_get_all_cochain_params_with_max_dim_one_and_no_top_features():
house_complex = get_house_complex()
params = house_complex.get_all_cochain_params(max_dim=1, include_top_features=False)
assert len(params) == 2
v_cochain_params, e_cochain_params = params
v_up_attr = v_cochain_params.kwargs['up_attr']
expected_v_up_attr = torch.tensor([[1], [1], [4], [4], [2], [2], [3], [3], [6], [6], [5], [5]],
dtype=torch.float)
assert torch.equal(expected_v_up_attr, v_up_attr)
e_up_attr = e_cochain_params.kwargs['up_attr']
assert e_up_attr is None
assert e_cochain_params.up_index is not None
assert e_cochain_params.up_index.size(1) == 6
e_down_attr = e_cochain_params.kwargs['down_attr']
expected_e_down_attr = torch.tensor([[2], [2], [1], [1], [3], [3], [3], [3], [4], [4], [4], [4],
[3], [3], [4], [4], [5], [5]], dtype=torch.float)
assert torch.equal(expected_e_down_attr, e_down_attr)
| 2,318 | 41.163636 | 100 | py |
cwn | cwn-main/data/helper_test.py | import itertools
import torch
import networkx as nx
from torch_geometric.utils import convert
from torch_geometric.data import Data
def check_edge_index_are_the_same(upper_index, edge_index):
"""Checks that two edge/cell indexes are the same."""
# These two tensors should have the same content but in different order.
assert upper_index.size() == edge_index.size()
num_edges = edge_index.size(1)
edge_set1 = set()
edge_set2 = set()
for i in range(num_edges):
e1, e2 = edge_index[0, i].item(), edge_index[1, i].item()
edge1 = tuple(sorted([e1, e2]))
edge_set1.add(edge1)
e1, e2 = upper_index[0, i].item(), upper_index[1, i].item()
edge2 = tuple(sorted([e1, e2]))
edge_set2.add(edge2)
assert edge_set1 == edge_set2
def get_table(boundary_index):
"""Indexes each cell based on the boundary index."""
elements = boundary_index.size(1)
id_to_cell = dict()
for i in range(elements):
cell_id = boundary_index[1, i].item()
boundary = boundary_index[0, i].item()
if cell_id not in id_to_cell:
id_to_cell[cell_id] = []
id_to_cell[cell_id].append(boundary)
return id_to_cell
def check_edge_attr_are_the_same(boundary_index, ex, edge_index, edge_attr):
"""Checks that a pairs of edge attributes are identical."""
# The maximum node that has an edge must be the same.
assert boundary_index[0, :].max() == edge_index.max()
# The number of edges present in both tensors should be the same.
assert boundary_index.size(1) == edge_index.size(1)
id_to_edge = get_table(boundary_index)
edge_to_id = dict()
for edge_idx, edge in id_to_edge.items():
edge_to_id[tuple(sorted(edge))] = edge_idx
edges = boundary_index.size(1)
for i in range(edges):
e1, e2 = edge_index[0, i].item(), edge_index[1, i].item()
edge = tuple(sorted([e1, e2]))
edge_attr1 = ex[edge_to_id[edge]].squeeze()
edge_attr2 = edge_attr[i].squeeze()
# NB: edge feats may be multidimensional, so we cannot
# generally use the `==` operator here
assert torch.equal(edge_attr1, edge_attr2)
def get_rings(n, edge_index, max_ring):
"""Extracts the induced cycles from a graph using networkx."""
x = torch.zeros((n, 1))
data = Data(x, edge_index=edge_index)
graph = convert.to_networkx(data)
def is_cycle_edge(i1, i2, cycle):
if i2 == i1 + 1:
return True
if i1 == 0 and i2 == len(cycle) - 1:
return True
return False
def is_chordless(cycle):
for (i1, v1), (i2, v2) in itertools.combinations(enumerate(cycle), 2):
if not is_cycle_edge(i1, i2, cycle) and graph.has_edge(v1, v2):
return False
return True
nx_rings = set()
for cycle in nx.simple_cycles(graph):
# Because we need to use a DiGraph for this method, it will also return each edge
# as a cycle. So we skip these together with cycles above the maximum length.
if len(cycle) <= 2 or len(cycle) > max_ring:
continue
# We skip the cycles with chords
if not is_chordless(cycle):
continue
# Store the cycle in a canonical form
nx_rings.add(tuple(sorted(cycle)))
return nx_rings
def get_complex_rings(r_boundary_index, e_boundary_index):
"""Extracts the vertices that are part of a ring."""
# Construct the edge and ring tables
id_to_ring = get_table(r_boundary_index)
id_to_edge = get_table(e_boundary_index)
rings = set()
for ring, edges in id_to_ring.items():
# Compose the two tables to extract the vertices in the ring.
vertices = [vertex for edge in edges for vertex in id_to_edge[edge]]
# Eliminate duplicates.
vertices = set(vertices)
# Store the ring in sorted order.
rings.add(tuple(sorted(vertices)))
return rings
def compare_complexes(yielded, expected, include_down_adj):
"""Checks that two cell complexes are the same."""
assert yielded.dimension == expected.dimension
assert torch.equal(yielded.y, expected.y)
for dim in range(expected.dimension + 1):
y_cochain = yielded.cochains[dim]
e_cochain = expected.cochains[dim]
assert y_cochain.num_cells == e_cochain.num_cells
assert y_cochain.num_cells_up == e_cochain.num_cells_up
assert y_cochain.num_cells_up == e_cochain.num_cells_up
assert y_cochain.num_cells_down == e_cochain.num_cells_down, dim
assert torch.equal(y_cochain.x, e_cochain.x)
if dim > 0:
assert torch.equal(y_cochain.boundary_index, e_cochain.boundary_index)
if include_down_adj:
if y_cochain.lower_index is None:
assert e_cochain.lower_index is None
assert y_cochain.shared_boundaries is None
assert e_cochain.shared_boundaries is None
else:
assert torch.equal(y_cochain.lower_index, e_cochain.lower_index)
assert torch.equal(y_cochain.shared_boundaries, e_cochain.shared_boundaries)
else:
assert y_cochain.boundary_index is None and e_cochain.boundary_index is None
assert y_cochain.lower_index is None and e_cochain.lower_index is None
assert y_cochain.shared_boundaries is None and e_cochain.shared_boundaries is None
if dim < expected.dimension:
if y_cochain.upper_index is None:
assert e_cochain.upper_index is None
assert y_cochain.shared_coboundaries is None
assert e_cochain.shared_coboundaries is None
else:
assert torch.equal(y_cochain.upper_index, e_cochain.upper_index)
assert torch.equal(y_cochain.shared_coboundaries, e_cochain.shared_coboundaries)
else:
assert y_cochain.upper_index is None and e_cochain.upper_index is None
assert y_cochain.shared_coboundaries is None and e_cochain.shared_coboundaries is None
def compare_complexes_without_2feats(yielded, expected, include_down_adj):
"""Checks that two cell complexes are the same, except for the features of the 2-cells."""
assert yielded.dimension == expected.dimension
assert torch.equal(yielded.y, expected.y)
for dim in range(expected.dimension + 1):
y_cochain = yielded.cochains[dim]
e_cochain = expected.cochains[dim]
assert y_cochain.num_cells == e_cochain.num_cells
assert y_cochain.num_cells_up == e_cochain.num_cells_up
assert y_cochain.num_cells_up == e_cochain.num_cells_up
assert y_cochain.num_cells_down == e_cochain.num_cells_down, dim
if dim > 0:
assert torch.equal(y_cochain.boundary_index, e_cochain.boundary_index)
if include_down_adj:
if y_cochain.lower_index is None:
assert e_cochain.lower_index is None
assert y_cochain.shared_boundaries is None
assert e_cochain.shared_boundaries is None
else:
assert torch.equal(y_cochain.lower_index, e_cochain.lower_index)
assert torch.equal(y_cochain.shared_boundaries, e_cochain.shared_boundaries)
else:
assert y_cochain.boundary_index is None and e_cochain.boundary_index is None
assert y_cochain.lower_index is None and e_cochain.lower_index is None
assert y_cochain.shared_boundaries is None and e_cochain.shared_boundaries is None
if dim < expected.dimension:
if y_cochain.upper_index is None:
assert e_cochain.upper_index is None
assert y_cochain.shared_coboundaries is None
assert e_cochain.shared_coboundaries is None
else:
assert torch.equal(y_cochain.upper_index, e_cochain.upper_index)
assert torch.equal(y_cochain.shared_coboundaries, e_cochain.shared_coboundaries)
else:
assert y_cochain.upper_index is None and e_cochain.upper_index is None
assert y_cochain.shared_coboundaries is None and e_cochain.shared_coboundaries is None
if dim != 2:
assert torch.equal(y_cochain.x, e_cochain.x)
else:
assert y_cochain.x is None and e_cochain.x is None
| 8,463 | 41.532663 | 98 | py |
cwn | cwn-main/data/data_loading.py | """
Code is adapted from https://github.com/rusty1s/pytorch_geometric/blob/6442a6e287563b39dae9f5fcffc52cd780925f89/torch_geometric/data/dataloader.py
Copyright (c) 2020 Matthias Fey <[email protected]>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os
import torch
from torch.utils.data.dataloader import default_collate
from torch_geometric.data import Data, Batch
from torch._six import container_abcs, string_classes, int_classes
from definitions import ROOT_DIR
from data.complex import Cochain, CochainBatch, Complex, ComplexBatch
from data.datasets import (
load_sr_graph_dataset, load_tu_graph_dataset, load_zinc_graph_dataset, load_ogb_graph_dataset,
load_ring_transfer_dataset, load_ring_lookup_dataset, load_pep_f_graph_dataset, load_pep_s_graph_dataset)
from data.datasets import (
SRDataset, ClusterDataset, TUDataset, ComplexDataset, FlowDataset,
OceanDataset, ZincDataset, CSLDataset, OGBDataset, RingTransferDataset, RingLookupDataset,
DummyDataset, DummyMolecularDataset, PeptidesFunctionalDataset, PeptidesStructuralDataset)
class Collater(object):
"""Object that converts python lists of objects into the appropiate storage format.
Args:
follow_batch: Creates assignment batch vectors for each key in the list.
max_dim: The maximum dimension of the cochains considered from the supplied list.
"""
def __init__(self, follow_batch, max_dim=2):
self.follow_batch = follow_batch
self.max_dim = max_dim
def collate(self, batch):
"""Converts a data list in the right storage format."""
elem = batch[0]
if isinstance(elem, Cochain):
return CochainBatch.from_cochain_list(batch, self.follow_batch)
elif isinstance(elem, Complex):
return ComplexBatch.from_complex_list(batch, self.follow_batch, max_dim=self.max_dim)
elif isinstance(elem, Data):
return Batch.from_data_list(batch, self.follow_batch)
elif isinstance(elem, torch.Tensor):
return default_collate(batch)
elif isinstance(elem, float):
return torch.tensor(batch, dtype=torch.float)
elif isinstance(elem, int_classes):
return torch.tensor(batch)
elif isinstance(elem, string_classes):
return batch
elif isinstance(elem, container_abcs.Mapping):
return {key: self.collate([d[key] for d in batch]) for key in elem}
elif isinstance(elem, tuple) and hasattr(elem, '_fields'):
return type(elem)(*(self.collate(s) for s in zip(*batch)))
elif isinstance(elem, container_abcs.Sequence):
return [self.collate(s) for s in zip(*batch)]
raise TypeError('DataLoader found invalid type: {}'.format(type(elem)))
def __call__(self, batch):
return self.collate(batch)
class DataLoader(torch.utils.data.DataLoader):
r"""Data loader which merges cochain complexes into to a mini-batch.
Args:
dataset (Dataset): The dataset from which to load the data.
batch_size (int, optional): How many samples per batch to load.
(default: :obj:`1`)
shuffle (bool, optional): If set to :obj:`True`, the data will be
reshuffled at every epoch. (default: :obj:`False`)
follow_batch (list or tuple, optional): Creates assignment batch
vectors for each key in the list. (default: :obj:`[]`)
max_dim (int): The maximum dimension of the chains to be used in the batch.
(default: 2)
"""
def __init__(self, dataset, batch_size=1, shuffle=False, follow_batch=[],
max_dim=2, **kwargs):
if "collate_fn" in kwargs:
del kwargs["collate_fn"]
# Save for Pytorch Lightning...
self.follow_batch = follow_batch
super(DataLoader,
self).__init__(dataset, batch_size, shuffle,
collate_fn=Collater(follow_batch, max_dim), **kwargs)
def load_dataset(name, root=os.path.join(ROOT_DIR, 'datasets'), max_dim=2, fold=0,
init_method='sum', n_jobs=2, **kwargs) -> ComplexDataset:
"""Returns a ComplexDataset with the specified name and initialised with the given params."""
if name.startswith('sr'):
dataset = SRDataset(os.path.join(root, 'SR_graphs'), name, max_dim=max_dim,
num_classes=16, max_ring_size=kwargs.get('max_ring_size', None),
n_jobs=n_jobs, init_method=init_method)
elif name == 'CLUSTER':
dataset = ClusterDataset(os.path.join(root, 'CLUSTER'), max_dim)
elif name == 'IMDBBINARY':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=True, init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'IMDBMULTI':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=3,
fold=fold, degree_as_tag=True, init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'REDDITBINARY':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=False, init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'REDDITMULTI5K':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=5,
fold=fold, degree_as_tag=False, init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'PROTEINS':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=False, include_down_adj=kwargs['include_down_adj'],
init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'NCI1':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=False, include_down_adj=kwargs['include_down_adj'],
init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'NCI109':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=False, include_down_adj=kwargs['include_down_adj'],
init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'PTC':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=False, include_down_adj=kwargs['include_down_adj'],
init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'MUTAG':
dataset = TUDataset(os.path.join(root, name), name, max_dim=max_dim, num_classes=2,
fold=fold, degree_as_tag=False, include_down_adj=kwargs['include_down_adj'],
init_method=init_method, max_ring_size=kwargs.get('max_ring_size', None))
elif name == 'FLOW':
dataset = FlowDataset(os.path.join(root, name), name, num_points=kwargs['flow_points'],
train_samples=1000, val_samples=200, train_orient=kwargs['train_orient'],
test_orient=kwargs['test_orient'], n_jobs=n_jobs)
elif name == 'OCEAN':
dataset = OceanDataset(os.path.join(root, name), name, train_orient=kwargs['train_orient'],
test_orient=kwargs['test_orient'])
elif name == 'RING-TRANSFER':
dataset = RingTransferDataset(os.path.join(root, name), nodes=kwargs['max_ring_size'])
elif name == 'RING-LOOKUP':
dataset = RingLookupDataset(os.path.join(root, name), nodes=kwargs['max_ring_size'])
elif name == 'ZINC':
dataset = ZincDataset(os.path.join(root, name), max_ring_size=kwargs['max_ring_size'],
include_down_adj=kwargs['include_down_adj'],
use_edge_features=kwargs['use_edge_features'], n_jobs=n_jobs)
elif name == 'ZINC-FULL':
dataset = ZincDataset(os.path.join(root, name), subset=False, max_ring_size=kwargs['max_ring_size'],
include_down_adj=kwargs['include_down_adj'],
use_edge_features=kwargs['use_edge_features'], n_jobs=n_jobs)
elif name == 'CSL':
dataset = CSLDataset(os.path.join(root, name), max_ring_size=kwargs['max_ring_size'],
fold=fold, n_jobs=n_jobs)
elif name in ['MOLHIV', 'MOLPCBA', 'MOLTOX21', 'MOLTOXCAST', 'MOLMUV',
'MOLBACE', 'MOLBBBP', 'MOLCLINTOX', 'MOLSIDER', 'MOLESOL',
'MOLFREESOLV', 'MOLLIPO']:
official_name = 'ogbg-'+name.lower()
dataset = OGBDataset(os.path.join(root, name), official_name, max_ring_size=kwargs['max_ring_size'],
use_edge_features=kwargs['use_edge_features'], simple=kwargs['simple_features'],
include_down_adj=kwargs['include_down_adj'], init_method=init_method, n_jobs=n_jobs)
elif name == 'DUMMY':
dataset = DummyDataset(os.path.join(root, name))
elif name == 'DUMMYM':
dataset = DummyMolecularDataset(os.path.join(root, name))
elif name == 'PEPTIDES-F':
dataset = PeptidesFunctionalDataset(os.path.join(root, name), max_ring_size=kwargs['max_ring_size'],
include_down_adj=kwargs['include_down_adj'], init_method=init_method, n_jobs=n_jobs)
elif name == 'PEPTIDES-S':
dataset = PeptidesStructuralDataset(os.path.join(root, name), max_ring_size=kwargs['max_ring_size'],
include_down_adj=kwargs['include_down_adj'], init_method=init_method, n_jobs=n_jobs)
else:
raise NotImplementedError(name)
return dataset
def load_graph_dataset(name, root=os.path.join(ROOT_DIR, 'datasets'), fold=0, **kwargs):
"""Returns a graph dataset with the specified name and initialised with the given params."""
if name.startswith('sr'):
graph_list, train_ids, val_ids, test_ids = load_sr_graph_dataset(name, root=root)
data = (graph_list, train_ids, val_ids, test_ids, None)
elif name == 'IMDBBINARY':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=True, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'IMDBMULTI':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=True, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 3)
elif name == 'REDDITBINARY':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'REDDITMULTI5K':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 5)
elif name == 'PROTEINS':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'NCI1':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'NCI109':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'PTC':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'MUTAG':
graph_list, train_ids, val_ids, test_ids = load_tu_graph_dataset(name, root=root, degree_as_tag=False, fold=fold, seed=0)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'ZINC':
graph_list, train_ids, val_ids, test_ids = load_zinc_graph_dataset(root=root)
data = (graph_list, train_ids, val_ids, test_ids, 1)
elif name == 'PEPTIDES-F':
graph_list, train_ids, val_ids, test_ids = load_pep_f_graph_dataset(root=root)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'PEPTIDES-S':
graph_list, train_ids, val_ids, test_ids = load_pep_s_graph_dataset(root=root)
data = (graph_list, train_ids, val_ids, test_ids, 2)
elif name == 'ZINC-FULL':
graph_list, train_ids, val_ids, test_ids = load_zinc_graph_dataset(root=root, subset=False)
data = (graph_list, train_ids, val_ids, test_ids, 1)
elif name in ['MOLHIV', 'MOLPCBA', 'MOLTOX21', 'MOLTOXCAST', 'MOLMUV',
'MOLBACE', 'MOLBBBP', 'MOLCLINTOX', 'MOLSIDER', 'MOLESOL',
'MOLFREESOLV', 'MOLLIPO']:
graph_list, train_ids, val_ids, test_ids = load_ogb_graph_dataset(
os.path.join(root, name), 'ogbg-'+name.lower())
data = (graph_list, train_ids, val_ids, test_ids, graph_list.num_tasks)
elif name == 'RING-TRANSFER':
graph_list, train_ids, val_ids, test_ids = load_ring_transfer_dataset(
nodes=kwargs['max_ring_size'], num_classes=5)
data = (graph_list, train_ids, val_ids, test_ids, 5)
elif name == 'RING-LOOKUP':
graph_list, train_ids, val_ids, test_ids = load_ring_lookup_dataset(
nodes=kwargs['max_ring_size'])
data = (graph_list, train_ids, val_ids, test_ids, kwargs['max_ring_size'] - 1)
else:
raise NotImplementedError
return data
| 14,860 | 56.378378 | 146 | py |
cwn | cwn-main/data/tu_utils.py | """
Based on code from https://github.com/weihua916/powerful-gnns/blob/master/util.py
MIT License
Copyright (c) 2021 Weihua Hu
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import networkx as nx
import numpy as np
import torch
import torch_geometric
from torch_geometric.data import Data
from sklearn.model_selection import StratifiedKFold
class S2VGraph(object):
def __init__(self, g, label, node_tags=None, node_features=None):
"""
g: a networkx graph
label: an integer graph label
node_tags: a list of integer node tags
node_features: a torch float tensor, one-hot representation of the tag that is used as input to neural nets
edge_mat: a torch long tensor, contain edge list, will be used to create torch sparse tensor
neighbors: list of neighbors (without self-loop)
"""
self.label = label
self.g = g
self.node_tags = node_tags
self.neighbors = []
self.node_features = 0
self.edge_mat = 0
self.max_neighbor = 0
def load_data(path, dataset, degree_as_tag):
"""
dataset: name of dataset
test_proportion: ratio of test train split
seed: random seed for random splitting of dataset
"""
print('loading data')
g_list = []
label_dict = {}
feat_dict = {}
with open('%s/%s.txt' % (path, dataset), 'r') as f:
n_g = int(f.readline().strip())
for i in range(n_g):
row = f.readline().strip().split()
n, l = [int(w) for w in row]
if not l in label_dict:
mapped = len(label_dict)
label_dict[l] = mapped
g = nx.Graph()
node_tags = []
node_features = []
n_edges = 0
for j in range(n):
g.add_node(j)
row = f.readline().strip().split()
tmp = int(row[1]) + 2
if tmp == len(row):
# no node attributes
row = [int(w) for w in row]
attr = None
else:
row, attr = [int(w) for w in row[:tmp]], np.array([float(w) for w in row[tmp:]])
if not row[0] in feat_dict:
mapped = len(feat_dict)
feat_dict[row[0]] = mapped
node_tags.append(feat_dict[row[0]])
if tmp > len(row):
node_features.append(attr)
n_edges += row[1]
for k in range(2, len(row)):
g.add_edge(j, row[k])
if node_features != []:
node_features = np.stack(node_features)
node_feature_flag = True
else:
node_features = None
node_feature_flag = False
assert len(g) == n
g_list.append(S2VGraph(g, l, node_tags))
#add labels and edge_mat
for g in g_list:
g.neighbors = [[] for i in range(len(g.g))]
for i, j in g.g.edges():
g.neighbors[i].append(j)
g.neighbors[j].append(i)
degree_list = []
for i in range(len(g.g)):
g.neighbors[i] = g.neighbors[i]
degree_list.append(len(g.neighbors[i]))
g.max_neighbor = max(degree_list)
g.label = label_dict[g.label]
edges = [list(pair) for pair in g.g.edges()]
edges.extend([[i, j] for j, i in edges])
deg_list = list(dict(g.g.degree(range(len(g.g)))).values()) # <- this might not be used...!?
g.edge_mat = torch.LongTensor(edges).transpose(0,1)
if degree_as_tag:
for g in g_list:
g.node_tags = list(dict(g.g.degree).values())
# ^^^ !? it should probably be replaced by the following one:
# g.node_tags = [g.g.degree[node] for node in range(len(g.g))]
#Extracting unique tag labels
tagset = set([])
for g in g_list:
tagset = tagset.union(set(g.node_tags))
tagset = list(tagset)
tag2index = {tagset[i]:i for i in range(len(tagset))}
for g in g_list:
g.node_features = torch.zeros(len(g.node_tags), len(tagset))
g.node_features[range(len(g.node_tags)), [tag2index[tag] for tag in g.node_tags]] = 1
# ==================
# Here we recompute degree encodings with external code,
# as we observed some unexpected behaviors likely due to
# incompatibilities w.r.t. python versions
# ==================
def get_node_degrees(graph):
edge_index = graph.edge_mat
if edge_index.shape[1] == 0: # just isolated nodes
degrees = torch.zeros((graph.node_features.shape[0],1))
else:
degrees = torch_geometric.utils.degree(edge_index[0]).unsqueeze(1)
return degrees
if degree_as_tag:
# 1. cumulate node degrees
degs = torch.cat([get_node_degrees(graph) for graph in g_list], 0)
# 2. compute unique values
uniques, corrs = np.unique(degs, return_inverse=True, axis=0)
# 3. encode
pointer = 0
for graph in g_list:
n = graph.node_features.shape[0]
hots = torch.LongTensor(corrs[pointer:pointer+n])
graph.node_features = torch.nn.functional.one_hot(hots, len(uniques)).float()
pointer += n
# ====================
print('# classes: %d' % len(label_dict))
print('# maximum node tag: %d' % len(tagset))
print("# data: %d" % len(g_list))
return g_list, len(label_dict)
def S2V_to_PyG(data):
new_data = Data()
setattr(new_data, 'edge_index', data.edge_mat)
setattr(new_data, 'x', data.node_features)
setattr(new_data, 'num_nodes', data.node_features.shape[0])
setattr(new_data, 'y', torch.tensor(data.label).unsqueeze(0).long())
return new_data
def separate_data(graph_list, seed, fold_idx):
assert 0 <= fold_idx and fold_idx < 10, "fold_idx must be from 0 to 9."
skf = StratifiedKFold(n_splits=10, shuffle = True, random_state = seed)
labels = [graph.label for graph in graph_list]
idx_list = []
for idx in skf.split(np.zeros(len(labels)), labels):
idx_list.append(idx)
train_idx, test_idx = idx_list[fold_idx]
train_graph_list = [graph_list[i] for i in train_idx]
test_graph_list = [graph_list[i] for i in test_idx]
return train_graph_list, test_graph_list
def separate_data_given_split(graph_list, path, fold_idx):
### Splits data based on pre-computed splits
assert -1 <= fold_idx and fold_idx < 10, "fold_idx must be from 0 to 9."
train_filename = os.path.join(path, '10fold_idx', 'train_idx-{}.txt'.format(fold_idx+1))
test_filename = os.path.join(path, '10fold_idx', 'test_idx-{}.txt'.format(fold_idx+1))
train_idx = np.loadtxt(train_filename, dtype=int)
test_idx = np.loadtxt(test_filename, dtype=int)
train_graph_list = [graph_list[i] for i in train_idx]
test_graph_list = [graph_list[i] for i in test_idx]
return train_graph_list, test_graph_list
def get_fold_indices(complex_list, seed, fold_idx):
assert 0 <= fold_idx and fold_idx < 10, "fold_idx must be from 0 to 9."
skf = StratifiedKFold(n_splits=10, shuffle = True, random_state = seed)
labels = [complex.y.item() for complex in complex_list]
idx_list = []
for idx in skf.split(np.zeros(len(labels)), labels):
idx_list.append(idx)
train_idx, test_idx = idx_list[fold_idx]
return train_idx.tolist(), test_idx.tolist()
| 8,611 | 34.883333 | 119 | py |
cwn | cwn-main/data/utils.py | import graph_tool as gt
import graph_tool.topology as top
import numpy as np
import torch
import gudhi as gd
import itertools
import networkx as nx
from tqdm import tqdm
from data.complex import Cochain, Complex
from typing import List, Dict, Optional, Union
from torch import Tensor
from torch_geometric.typing import Adj
from torch_scatter import scatter
from data.parallel import ProgressParallel
from joblib import delayed
def pyg_to_simplex_tree(edge_index: Tensor, size: int):
"""Constructs a simplex tree from a PyG graph.
Args:
edge_index: The edge_index of the graph (a tensor of shape [2, num_edges])
size: The number of nodes in the graph.
"""
st = gd.SimplexTree()
# Add vertices to the simplex.
for v in range(size):
st.insert([v])
# Add the edges to the simplex.
edges = edge_index.numpy()
for e in range(edges.shape[1]):
edge = [edges[0][e], edges[1][e]]
st.insert(edge)
return st
def get_simplex_boundaries(simplex):
boundaries = itertools.combinations(simplex, len(simplex) - 1)
return [tuple(boundary) for boundary in boundaries]
def build_tables(simplex_tree, size):
complex_dim = simplex_tree.dimension()
# Each of these data structures has a separate entry per dimension.
id_maps = [{} for _ in range(complex_dim+1)] # simplex -> id
simplex_tables = [[] for _ in range(complex_dim+1)] # matrix of simplices
boundaries_tables = [[] for _ in range(complex_dim+1)]
simplex_tables[0] = [[v] for v in range(size)]
id_maps[0] = {tuple([v]): v for v in range(size)}
for simplex, _ in simplex_tree.get_simplices():
dim = len(simplex) - 1
if dim == 0:
continue
# Assign this simplex the next unused ID
next_id = len(simplex_tables[dim])
id_maps[dim][tuple(simplex)] = next_id
simplex_tables[dim].append(simplex)
return simplex_tables, id_maps
def extract_boundaries_and_coboundaries_from_simplex_tree(simplex_tree, id_maps, complex_dim: int):
"""Build two maps simplex -> its coboundaries and simplex -> its boundaries"""
# The extra dimension is added just for convenience to avoid treating it as a special case.
boundaries = [{} for _ in range(complex_dim+2)] # simplex -> boundaries
coboundaries = [{} for _ in range(complex_dim+2)] # simplex -> coboundaries
boundaries_tables = [[] for _ in range(complex_dim+1)]
for simplex, _ in simplex_tree.get_simplices():
# Extract the relevant boundary and coboundary maps
simplex_dim = len(simplex) - 1
level_coboundaries = coboundaries[simplex_dim]
level_boundaries = boundaries[simplex_dim + 1]
# Add the boundaries of the simplex to the boundaries table
if simplex_dim > 0:
boundaries_ids = [id_maps[simplex_dim-1][boundary] for boundary in get_simplex_boundaries(simplex)]
boundaries_tables[simplex_dim].append(boundaries_ids)
# This operation should be roughly be O(dim_complex), so that is very efficient for us.
# For details see pages 6-7 https://hal.inria.fr/hal-00707901v1/document
simplex_coboundaries = simplex_tree.get_cofaces(simplex, codimension=1)
for coboundary, _ in simplex_coboundaries:
assert len(coboundary) == len(simplex) + 1
if tuple(simplex) not in level_coboundaries:
level_coboundaries[tuple(simplex)] = list()
level_coboundaries[tuple(simplex)].append(tuple(coboundary))
if tuple(coboundary) not in level_boundaries:
level_boundaries[tuple(coboundary)] = list()
level_boundaries[tuple(coboundary)].append(tuple(simplex))
return boundaries_tables, boundaries, coboundaries
def build_adj(boundaries: List[Dict], coboundaries: List[Dict], id_maps: List[Dict], complex_dim: int,
include_down_adj: bool):
"""Builds the upper and lower adjacency data structures of the complex
Args:
boundaries: A list of dictionaries of the form
boundaries[dim][simplex] -> List[simplex] (the boundaries)
coboundaries: A list of dictionaries of the form
coboundaries[dim][simplex] -> List[simplex] (the coboundaries)
id_maps: A dictionary from simplex -> simplex_id
"""
def initialise_structure():
return [[] for _ in range(complex_dim+1)]
upper_indexes, lower_indexes = initialise_structure(), initialise_structure()
all_shared_boundaries, all_shared_coboundaries = initialise_structure(), initialise_structure()
# Go through all dimensions of the complex
for dim in range(complex_dim+1):
# Go through all the simplices at that dimension
for simplex, id in id_maps[dim].items():
# Add the upper adjacent neighbours from the level below
if dim > 0:
for boundary1, boundary2 in itertools.combinations(boundaries[dim][simplex], 2):
id1, id2 = id_maps[dim - 1][boundary1], id_maps[dim - 1][boundary2]
upper_indexes[dim - 1].extend([[id1, id2], [id2, id1]])
all_shared_coboundaries[dim - 1].extend([id, id])
# Add the lower adjacent neighbours from the level above
if include_down_adj and dim < complex_dim and simplex in coboundaries[dim]:
for coboundary1, coboundary2 in itertools.combinations(coboundaries[dim][simplex], 2):
id1, id2 = id_maps[dim + 1][coboundary1], id_maps[dim + 1][coboundary2]
lower_indexes[dim + 1].extend([[id1, id2], [id2, id1]])
all_shared_boundaries[dim + 1].extend([id, id])
return all_shared_boundaries, all_shared_coboundaries, lower_indexes, upper_indexes
def construct_features(vx: Tensor, cell_tables, init_method: str) -> List:
"""Combines the features of the component vertices to initialise the cell features"""
features = [vx]
for dim in range(1, len(cell_tables)):
aux_1 = []
aux_0 = []
for c, cell in enumerate(cell_tables[dim]):
aux_1 += [c for _ in range(len(cell))]
aux_0 += cell
node_cell_index = torch.LongTensor([aux_0, aux_1])
in_features = vx.index_select(0, node_cell_index[0])
features.append(scatter(in_features, node_cell_index[1], dim=0,
dim_size=len(cell_tables[dim]), reduce=init_method))
return features
def extract_labels(y, size):
v_y, complex_y = None, None
if y is None:
return v_y, complex_y
y_shape = list(y.size())
if y_shape[0] == 1:
# This is a label for the whole graph (for graph classification).
# We will use it for the complex.
complex_y = y
else:
# This is a label for the vertices of the complex.
assert y_shape[0] == size
v_y = y
return v_y, complex_y
def generate_cochain(dim, x, all_upper_index, all_lower_index,
all_shared_boundaries, all_shared_coboundaries, cell_tables, boundaries_tables,
complex_dim, y=None):
"""Builds a Cochain given all the adjacency data extracted from the complex."""
if dim == 0:
assert len(all_lower_index[dim]) == 0
assert len(all_shared_boundaries[dim]) == 0
num_cells_down = len(cell_tables[dim-1]) if dim > 0 else None
num_cells_up = len(cell_tables[dim+1]) if dim < complex_dim else 0
up_index = (torch.tensor(all_upper_index[dim], dtype=torch.long).t()
if len(all_upper_index[dim]) > 0 else None)
down_index = (torch.tensor(all_lower_index[dim], dtype=torch.long).t()
if len(all_lower_index[dim]) > 0 else None)
shared_coboundaries = (torch.tensor(all_shared_coboundaries[dim], dtype=torch.long)
if len(all_shared_coboundaries[dim]) > 0 else None)
shared_boundaries = (torch.tensor(all_shared_boundaries[dim], dtype=torch.long)
if len(all_shared_boundaries[dim]) > 0 else None)
boundary_index = None
if len(boundaries_tables[dim]) > 0:
boundary_index = [list(), list()]
for s, cell in enumerate(boundaries_tables[dim]):
for boundary in cell:
boundary_index[1].append(s)
boundary_index[0].append(boundary)
boundary_index = torch.LongTensor(boundary_index)
if num_cells_down is None:
assert shared_boundaries is None
if num_cells_up == 0:
assert shared_coboundaries is None
if up_index is not None:
assert up_index.size(1) == shared_coboundaries.size(0)
assert num_cells_up == shared_coboundaries.max() + 1
if down_index is not None:
assert down_index.size(1) == shared_boundaries.size(0)
assert num_cells_down >= shared_boundaries.max() + 1
return Cochain(dim=dim, x=x, upper_index=up_index,
lower_index=down_index, shared_coboundaries=shared_coboundaries,
shared_boundaries=shared_boundaries, y=y, num_cells_down=num_cells_down,
num_cells_up=num_cells_up, boundary_index=boundary_index)
def compute_clique_complex_with_gudhi(x: Tensor, edge_index: Adj, size: int,
expansion_dim: int = 2, y: Tensor = None,
include_down_adj=True,
init_method: str = 'sum') -> Complex:
"""Generates a clique complex of a pyG graph via gudhi.
Args:
x: The feature matrix for the nodes of the graph
edge_index: The edge_index of the graph (a tensor of shape [2, num_edges])
size: The number of nodes in the graph
expansion_dim: The dimension to expand the simplex to.
y: Labels for the graph nodes or a label for the whole graph.
include_down_adj: Whether to add down adj in the complex or not
init_method: How to initialise features at higher levels.
"""
assert x is not None
assert isinstance(edge_index, Tensor) # Support only tensor edge_index for now
# Creates the gudhi-based simplicial complex
simplex_tree = pyg_to_simplex_tree(edge_index, size)
simplex_tree.expansion(expansion_dim) # Computes the clique complex up to the desired dim.
complex_dim = simplex_tree.dimension() # See what is the dimension of the complex now.
# Builds tables of the simplicial complexes at each level and their IDs
simplex_tables, id_maps = build_tables(simplex_tree, size)
# Extracts the boundaries and coboundaries of each simplex in the complex
boundaries_tables, boundaries, co_boundaries = (
extract_boundaries_and_coboundaries_from_simplex_tree(simplex_tree, id_maps, complex_dim))
# Computes the adjacencies between all the simplexes in the complex
shared_boundaries, shared_coboundaries, lower_idx, upper_idx = build_adj(boundaries, co_boundaries, id_maps,
complex_dim, include_down_adj)
# Construct features for the higher dimensions
# TODO: Make this handle edge features as well and add alternative options to compute this.
xs = construct_features(x, simplex_tables, init_method)
# Initialise the node / complex labels
v_y, complex_y = extract_labels(y, size)
cochains = []
for i in range(complex_dim+1):
y = v_y if i == 0 else None
cochain = generate_cochain(i, xs[i], upper_idx, lower_idx, shared_boundaries, shared_coboundaries,
simplex_tables, boundaries_tables, complex_dim=complex_dim, y=y)
cochains.append(cochain)
return Complex(*cochains, y=complex_y, dimension=complex_dim)
def convert_graph_dataset_with_gudhi(dataset, expansion_dim: int, include_down_adj=True,
init_method: str = 'sum'):
# TODO(Cris): Add parallelism to this code like in the cell complex conversion code.
dimension = -1
complexes = []
num_features = [None for _ in range(expansion_dim+1)]
for data in tqdm(dataset):
complex = compute_clique_complex_with_gudhi(data.x, data.edge_index, data.num_nodes,
expansion_dim=expansion_dim, y=data.y, include_down_adj=include_down_adj,
init_method=init_method)
if complex.dimension > dimension:
dimension = complex.dimension
for dim in range(complex.dimension + 1):
if num_features[dim] is None:
num_features[dim] = complex.cochains[dim].num_features
else:
assert num_features[dim] == complex.cochains[dim].num_features
complexes.append(complex)
return complexes, dimension, num_features[:dimension+1]
# ---- support for rings as cells
def get_rings(edge_index, max_k=7):
if isinstance(edge_index, torch.Tensor):
edge_index = edge_index.numpy()
edge_list = edge_index.T
graph_gt = gt.Graph(directed=False)
graph_gt.add_edge_list(edge_list)
gt.stats.remove_self_loops(graph_gt)
gt.stats.remove_parallel_edges(graph_gt)
# We represent rings with their original node ordering
# so that we can easily read out the boundaries
# The use of the `sorted_rings` set allows to discard
# different isomorphisms which are however associated
# to the same original ring – this happens due to the intrinsic
# symmetries of cycles
rings = set()
sorted_rings = set()
for k in range(3, max_k+1):
pattern = nx.cycle_graph(k)
pattern_edge_list = list(pattern.edges)
pattern_gt = gt.Graph(directed=False)
pattern_gt.add_edge_list(pattern_edge_list)
sub_isos = top.subgraph_isomorphism(pattern_gt, graph_gt, induced=True, subgraph=True,
generator=True)
sub_iso_sets = map(lambda isomorphism: tuple(isomorphism.a), sub_isos)
for iso in sub_iso_sets:
if tuple(sorted(iso)) not in sorted_rings:
rings.add(iso)
sorted_rings.add(tuple(sorted(iso)))
rings = list(rings)
return rings
def build_tables_with_rings(edge_index, simplex_tree, size, max_k):
# Build simplex tables and id_maps up to edges by conveniently
# invoking the code for simplicial complexes
cell_tables, id_maps = build_tables(simplex_tree, size)
# Find rings in the graph
rings = get_rings(edge_index, max_k=max_k)
if len(rings) > 0:
# Extend the tables with rings as 2-cells
id_maps += [{}]
cell_tables += [[]]
assert len(cell_tables) == 3, cell_tables
for cell in rings:
next_id = len(cell_tables[2])
id_maps[2][cell] = next_id
cell_tables[2].append(list(cell))
return cell_tables, id_maps
def get_ring_boundaries(ring):
boundaries = list()
for n in range(len(ring)):
a = n
if n + 1 == len(ring):
b = 0
else:
b = n + 1
# We represent the boundaries in lexicographic order
# so to be compatible with 0- and 1- dim cells
# extracted as simplices with gudhi
boundaries.append(tuple(sorted([ring[a], ring[b]])))
return sorted(boundaries)
def extract_boundaries_and_coboundaries_with_rings(simplex_tree, id_maps):
"""Build two maps: cell -> its coboundaries and cell -> its boundaries"""
# Find boundaries and coboundaries up to edges by conveniently
# invoking the code for simplicial complexes
assert simplex_tree.dimension() <= 1
boundaries_tables, boundaries, coboundaries = extract_boundaries_and_coboundaries_from_simplex_tree(
simplex_tree, id_maps, simplex_tree.dimension())
assert len(id_maps) <= 3
if len(id_maps) == 3:
# Extend tables with boundary and coboundary information of rings
boundaries += [{}]
coboundaries += [{}]
boundaries_tables += [[]]
for cell in id_maps[2]:
cell_boundaries = get_ring_boundaries(cell)
boundaries[2][cell] = list()
boundaries_tables[2].append([])
for boundary in cell_boundaries:
assert boundary in id_maps[1], boundary
boundaries[2][cell].append(boundary)
if boundary not in coboundaries[1]:
coboundaries[1][boundary] = list()
coboundaries[1][boundary].append(cell)
boundaries_tables[2][-1].append(id_maps[1][boundary])
return boundaries_tables, boundaries, coboundaries
def compute_ring_2complex(x: Union[Tensor, np.ndarray], edge_index: Union[Tensor, np.ndarray],
edge_attr: Optional[Union[Tensor, np.ndarray]],
size: int, y: Optional[Union[Tensor, np.ndarray]] = None, max_k: int = 7,
include_down_adj=True, init_method: str = 'sum',
init_edges=True, init_rings=False) -> Complex:
"""Generates a ring 2-complex of a pyG graph via graph-tool.
Args:
x: The feature matrix for the nodes of the graph (shape [num_vertices, num_v_feats])
edge_index: The edge_index of the graph (a tensor of shape [2, num_edges])
edge_attr: The feature matrix for the edges of the graph (shape [num_edges, num_e_feats])
size: The number of nodes in the graph
y: Labels for the graph nodes or a label for the whole graph.
max_k: maximum length of rings to look for.
include_down_adj: Whether to add down adj in the complex or not
init_method: How to initialise features at higher levels.
"""
assert x is not None
assert isinstance(edge_index, np.ndarray) or isinstance(edge_index, Tensor)
# For parallel processing with joblib we need to pass numpy arrays as inputs
# Therefore, we convert here everything back to a tensor.
if isinstance(x, np.ndarray):
x = torch.tensor(x)
if isinstance(edge_index, np.ndarray):
edge_index = torch.tensor(edge_index)
if isinstance(edge_attr, np.ndarray):
edge_attr = torch.tensor(edge_attr)
if isinstance(y, np.ndarray):
y = torch.tensor(y)
# Creates the gudhi-based simplicial complex up to edges
simplex_tree = pyg_to_simplex_tree(edge_index, size)
assert simplex_tree.dimension() <= 1
if simplex_tree.dimension() == 0:
assert edge_index.size(1) == 0
# Builds tables of the cellular complexes at each level and their IDs
cell_tables, id_maps = build_tables_with_rings(edge_index, simplex_tree, size, max_k)
assert len(id_maps) <= 3
complex_dim = len(id_maps)-1
# Extracts the boundaries and coboundaries of each cell in the complex
boundaries_tables, boundaries, co_boundaries = extract_boundaries_and_coboundaries_with_rings(simplex_tree, id_maps)
# Computes the adjacencies between all the cells in the complex;
# here we force complex dimension to be 2
shared_boundaries, shared_coboundaries, lower_idx, upper_idx = build_adj(boundaries, co_boundaries, id_maps,
complex_dim, include_down_adj)
# Construct features for the higher dimensions
xs = [x, None, None]
constructed_features = construct_features(x, cell_tables, init_method)
if simplex_tree.dimension() == 0:
assert len(constructed_features) == 1
if init_rings and len(constructed_features) > 2:
xs[2] = constructed_features[2]
if init_edges and simplex_tree.dimension() >= 1:
if edge_attr is None:
xs[1] = constructed_features[1]
# If we have edge-features we simply use them for 1-cells
else:
# If edge_attr is a list of scalar features, make it a matrix
if edge_attr.dim() == 1:
edge_attr = edge_attr.view(-1, 1)
# Retrieve feats and check edge features are undirected
ex = dict()
for e, edge in enumerate(edge_index.numpy().T):
canon_edge = tuple(sorted(edge))
edge_id = id_maps[1][canon_edge]
edge_feats = edge_attr[e]
if edge_id in ex:
assert torch.equal(ex[edge_id], edge_feats)
else:
ex[edge_id] = edge_feats
# Build edge feature matrix
max_id = max(ex.keys())
edge_feats = []
assert len(cell_tables[1]) == max_id + 1
for id in range(max_id + 1):
edge_feats.append(ex[id])
xs[1] = torch.stack(edge_feats, dim=0)
assert xs[1].dim() == 2
assert xs[1].size(0) == len(id_maps[1])
assert xs[1].size(1) == edge_attr.size(1)
# Initialise the node / complex labels
v_y, complex_y = extract_labels(y, size)
cochains = []
for i in range(complex_dim + 1):
y = v_y if i == 0 else None
cochain = generate_cochain(i, xs[i], upper_idx, lower_idx, shared_boundaries, shared_coboundaries,
cell_tables, boundaries_tables, complex_dim=complex_dim, y=y)
cochains.append(cochain)
return Complex(*cochains, y=complex_y, dimension=complex_dim)
def convert_graph_dataset_with_rings(dataset, max_ring_size=7, include_down_adj=False,
init_method: str = 'sum', init_edges=True, init_rings=False,
n_jobs=1):
dimension = -1
num_features = [None, None, None]
def maybe_convert_to_numpy(x):
if isinstance(x, Tensor):
return x.numpy()
return x
# Process the dataset in parallel
parallel = ProgressParallel(n_jobs=n_jobs, use_tqdm=True, total=len(dataset))
# It is important we supply a numpy array here. tensors seem to slow joblib down significantly.
complexes = parallel(delayed(compute_ring_2complex)(
maybe_convert_to_numpy(data.x), maybe_convert_to_numpy(data.edge_index),
maybe_convert_to_numpy(data.edge_attr),
data.num_nodes, y=maybe_convert_to_numpy(data.y), max_k=max_ring_size,
include_down_adj=include_down_adj, init_method=init_method,
init_edges=init_edges, init_rings=init_rings) for data in dataset)
# NB: here we perform additional checks to verify the order of complexes
# corresponds to that of input graphs after _parallel_ conversion
for c, complex in enumerate(complexes):
# Handle dimension and number of features
if complex.dimension > dimension:
dimension = complex.dimension
for dim in range(complex.dimension + 1):
if num_features[dim] is None:
num_features[dim] = complex.cochains[dim].num_features
else:
assert num_features[dim] == complex.cochains[dim].num_features
# Validate against graph
graph = dataset[c]
if complex.y is None:
assert graph.y is None
else:
assert torch.equal(complex.y, graph.y)
assert torch.equal(complex.cochains[0].x, graph.x)
if complex.dimension >= 1:
assert complex.cochains[1].x.size(0) == (graph.edge_index.size(1) // 2)
return complexes, dimension, num_features[:dimension+1]
| 23,431 | 41.915751 | 120 | py |
cwn | cwn-main/data/complex.py | """
Copyright (c) 2020 Matthias Fey <[email protected]>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import torch
import logging
import copy
from torch import Tensor
from torch_sparse import SparseTensor
from mp.cell_mp import CochainMessagePassingParams
from torch_geometric.typing import Adj
from typing import List
class Cochain(object):
"""
Class representing a cochain on k-dim cells (i.e. vector-valued signals on k-dim cells).
Args:
dim: dim of the cells in the cochain
x: feature matrix, shape [num_cells, num_features]; may not be available
upper_index: upper adjacency, matrix, shape [2, num_upper_connections];
may not be available, e.g. when `dim` is the top level dim of a complex
lower_index: lower adjacency, matrix, shape [2, num_lower_connections];
may not be available, e.g. when `dim` is 0
shared_boundaries: a tensor of shape (num_lower_adjacencies,) specifying the indices of
the shared boundary for each lower adjacency
shared_coboundaries: a tensor of shape (num_upper_adjacencies,) specifying the indices of
the shared coboundary for each upper adjacency
boundary_index: boundary adjacency, matrix, shape [2, num_boundaries_connections];
may not be available, e.g. when `dim` is 0
upper_orient: a tensor of shape (num_upper_adjacencies,) specifying the relative
orientation (+-1) with respect to the cells from upper_index
lower_orient: a tensor of shape (num_lower_adjacencies,) specifying the relative
orientation (+-1) with respect to the cells from lower_index
y: labels over cells in the cochain, shape [num_cells,]
"""
def __init__(self, dim: int, x: Tensor = None, upper_index: Adj = None, lower_index: Adj = None,
shared_boundaries: Tensor = None, shared_coboundaries: Tensor = None, mapping: Tensor = None,
boundary_index: Adj = None, upper_orient=None, lower_orient=None, y=None, **kwargs):
if dim == 0:
assert lower_index is None
assert shared_boundaries is None
assert boundary_index is None
# Note, everything that is not of form __smth__ is made None during batching
# So dim must be stored like this.
self.__dim__ = dim
# TODO: check default for x
self.__x = x
self.upper_index = upper_index
self.lower_index = lower_index
self.boundary_index = boundary_index
self.y = y
self.shared_boundaries = shared_boundaries
self.shared_coboundaries = shared_coboundaries
self.upper_orient = upper_orient
self.lower_orient = lower_orient
self.__oriented__ = False
self.__hodge_laplacian__ = None
# TODO: Figure out what to do with mapping.
self.__mapping = mapping
for key, item in kwargs.items():
if key == 'num_cells':
self.__num_cells__ = item
elif key == 'num_cells_down':
self.num_cells_down = item
elif key == 'num_cells_up':
self.num_cells_up = item
else:
self[key] = item
@property
def dim(self):
"""Returns the dimension of the cells in this cochain.
This field should not have a setter. The dimension of a cochain cannot be changed.
"""
return self.__dim__
@property
def x(self):
"""Returns the vector values (features) associated with the cells."""
return self.__x
@x.setter
def x(self, new_x):
"""Sets the vector values (features) associated with the cells."""
if new_x is None:
logging.warning("Cochain features were set to None. ")
else:
assert self.num_cells == len(new_x)
self.__x = new_x
@property
def keys(self):
"""Returns all names of cochain attributes."""
keys = [key for key in self.__dict__.keys() if self[key] is not None]
keys = [key for key in keys if key[:2] != '__' and key[-2:] != '__']
return keys
def __getitem__(self, key):
"""Gets the data of the attribute :obj:`key`."""
return getattr(self, key, None)
def __setitem__(self, key, value):
"""Sets the attribute :obj:`key` to :obj:`value`."""
setattr(self, key, value)
def __contains__(self, key):
"""Returns :obj:`True`, if the attribute :obj:`key` is present in the data."""
return key in self.keys
def __cat_dim__(self, key, value):
"""
Returns the dimension for which :obj:`value` of attribute
:obj:`key` will get concatenated when creating batches.
"""
if key in ['upper_index', 'lower_index', 'shared_boundaries',
'shared_coboundaries', 'boundary_index']:
return -1
# by default, concatenate sparse matrices diagonally.
elif isinstance(value, SparseTensor):
return (0, 1)
return 0
def __inc__(self, key, value):
"""
Returns the incremental count to cumulatively increase the value
of the next attribute of :obj:`key` when creating batches.
"""
# TODO: value is not used in this method. Can it be removed?
if key in ['upper_index', 'lower_index']:
inc = self.num_cells
elif key in ['shared_boundaries']:
inc = self.num_cells_down
elif key == 'shared_coboundaries':
inc = self.num_cells_up
elif key == 'boundary_index':
boundary_inc = self.num_cells_down if self.num_cells_down is not None else 0
cell_inc = self.num_cells if self.num_cells is not None else 0
inc = [[boundary_inc], [cell_inc]]
else:
inc = 0
if inc is None:
inc = 0
return inc
def __call__(self, *keys):
"""
Iterates over all attributes :obj:`*keys` in the cochain, yielding
their attribute names and content.
If :obj:`*keys` is not given this method will iterative over all
present attributes.
"""
for key in sorted(self.keys) if not keys else keys:
if key in self:
yield key, self[key]
@property
def num_cells(self):
"""Returns the number of cells in the cochain."""
if hasattr(self, '__num_cells__'):
return self.__num_cells__
if self.x is not None:
return self.x.size(self.__cat_dim__('x', self.x))
if self.boundary_index is not None:
return int(self.boundary_index[1,:].max()) + 1
assert self.upper_index is None and self.lower_index is None
return None
@num_cells.setter
def num_cells(self, num_cells):
"""Sets the number of cells in the cochain."""
# TODO: Add more checks here
self.__num_cells__ = num_cells
@property
def num_cells_up(self):
"""Returns the number of cells in the higher-dimensional cochain of co-dimension 1."""
if hasattr(self, '__num_cells_up__'):
return self.__num_cells_up__
elif self.shared_coboundaries is not None:
assert self.upper_index is not None
return int(self.shared_coboundaries.max()) + 1
assert self.upper_index is None
return 0
@num_cells_up.setter
def num_cells_up(self, num_cells_up):
"""Sets the number of cells in the higher-dimensional cochain of co-dimension 1."""
# TODO: Add more checks here
self.__num_cells_up__ = num_cells_up
@property
def num_cells_down(self):
"""Returns the number of cells in the lower-dimensional cochain of co-dimension 1."""
if self.dim == 0:
return None
if hasattr(self, '__num_cells_down__'):
return self.__num_cells_down__
if self.lower_index is None:
return 0
raise ValueError('Cannot infer the number of cells in the cochain below.')
@num_cells_down.setter
def num_cells_down(self, num_cells_down):
"""Sets the number of cells in the lower-dimensional cochain of co-dimension 1."""
# TODO: Add more checks here
self.__num_cells_down__ = num_cells_down
@property
def num_features(self):
"""Returns the number of features per cell in the cochain."""
if self.x is None:
return 0
return 1 if self.x.dim() == 1 else self.x.size(1)
def __apply__(self, item, func):
if torch.is_tensor(item):
return func(item)
elif isinstance(item, SparseTensor):
# Not all apply methods are supported for `SparseTensor`, e.g.,
# `contiguous()`. We can get around it by capturing the exception.
try:
return func(item)
except AttributeError:
return item
elif isinstance(item, (tuple, list)):
return [self.__apply__(v, func) for v in item]
elif isinstance(item, dict):
return {k: self.__apply__(v, func) for k, v in item.items()}
else:
return item
def apply(self, func, *keys):
"""
Applies the function :obj:`func` to all tensor attributes
:obj:`*keys`. If :obj:`*keys` is not given, :obj:`func` is applied to
all present attributes.
"""
for key, item in self(*keys):
self[key] = self.__apply__(item, func)
return self
def contiguous(self, *keys):
"""
Ensures a contiguous memory layout for all attributes :obj:`*keys`.
If :obj:`*keys` is not given, all present attributes are ensured to
have a contiguous memory layout.
"""
return self.apply(lambda x: x.contiguous(), *keys)
def to(self, device, *keys, **kwargs):
"""
Performs tensor dtype and/or device conversion to all attributes
:obj:`*keys`.
If :obj:`*keys` is not given, the conversion is applied to all present
attributes.
"""
return self.apply(lambda x: x.to(device, **kwargs), *keys)
def clone(self):
return self.__class__.from_dict({
k: v.clone() if torch.is_tensor(v) else copy.deepcopy(v)
for k, v in self.__dict__.items()
})
@property
def mapping(self):
return self.__mapping
class CochainBatch(Cochain):
"""A datastructure for storing a batch of cochains.
Similarly to PyTorch Geometric, the batched cochain consists of a big cochain formed of multiple
independent cochains on sets of disconnected cells.
"""
def __init__(self, dim, batch=None, ptr=None, **kwargs):
super(CochainBatch, self).__init__(dim, **kwargs)
for key, item in kwargs.items():
if key == 'num_cells':
self.__num_cells__ = item
else:
self[key] = item
self.batch = batch
self.ptr = ptr
self.__data_class__ = Cochain
self.__slices__ = None
self.__cumsum__ = None
self.__cat_dims__ = None
self.__num_cells_list__ = None
self.__num_cells_down_list__ = None
self.__num_cells_up_list__ = None
self.__num_cochains__ = None
@classmethod
def from_cochain_list(cls, data_list, follow_batch=[]):
"""
Constructs a batch object from a python list holding
:class:`Cochain` objects.
The assignment vector :obj:`batch` is created on the fly.
Additionally, creates assignment batch vectors for each key in
:obj:`follow_batch`.
"""
keys = list(set.union(*[set(data.keys) for data in data_list]))
assert 'batch' not in keys and 'ptr' not in keys
batch = cls(data_list[0].dim)
for key in data_list[0].__dict__.keys():
if key[:2] != '__' and key[-2:] != '__':
batch[key] = None
batch.__num_cochains__ = len(data_list)
batch.__data_class__ = data_list[0].__class__
for key in keys + ['batch']:
batch[key] = []
batch['ptr'] = [0]
device = None
slices = {key: [0] for key in keys}
cumsum = {key: [0] for key in keys}
cat_dims = {}
num_cells_list = []
num_cells_up_list = []
num_cells_down_list = []
for i, data in enumerate(data_list):
for key in keys:
item = data[key]
if item is not None:
# Increase values by `cumsum` value.
cum = cumsum[key][-1]
if isinstance(item, Tensor) and item.dtype != torch.bool:
if not isinstance(cum, int) or cum != 0:
item = item + cum
elif isinstance(item, SparseTensor):
value = item.storage.value()
if value is not None and value.dtype != torch.bool:
if not isinstance(cum, int) or cum != 0:
value = value + cum
item = item.set_value(value, layout='coo')
elif isinstance(item, (int, float)):
item = item + cum
# Treat 0-dimensional tensors as 1-dimensional.
if isinstance(item, Tensor) and item.dim() == 0:
item = item.unsqueeze(0)
batch[key].append(item)
# Gather the size of the `cat` dimension.
size = 1
cat_dim = data.__cat_dim__(key, data[key])
cat_dims[key] = cat_dim
if isinstance(item, Tensor):
size = item.size(cat_dim)
device = item.device
elif isinstance(item, SparseTensor):
size = torch.tensor(item.sizes())[torch.tensor(cat_dim)]
device = item.device()
# TODO: do we really need slices, and, are we managing them correctly?
slices[key].append(size + slices[key][-1])
if key in follow_batch:
if isinstance(size, Tensor):
for j, size in enumerate(size.tolist()):
tmp = f'{key}_{j}_batch'
batch[tmp] = [] if i == 0 else batch[tmp]
batch[tmp].append(
torch.full((size, ), i, dtype=torch.long,
device=device))
else:
tmp = f'{key}_batch'
batch[tmp] = [] if i == 0 else batch[tmp]
batch[tmp].append(
torch.full((size, ), i, dtype=torch.long,
device=device))
inc = data.__inc__(key, item)
if isinstance(inc, (tuple, list)):
inc = torch.tensor(inc)
cumsum[key].append(inc + cumsum[key][-1])
if hasattr(data, '__num_cells__'):
num_cells_list.append(data.__num_cells__)
else:
num_cells_list.append(None)
if hasattr(data, '__num_cells_up__'):
num_cells_up_list.append(data.__num_cells_up__)
else:
num_cells_up_list.append(None)
if hasattr(data, '__num_cells_down__'):
num_cells_down_list.append(data.__num_cells_down__)
else:
num_cells_down_list.append(None)
num_cells = data.num_cells
if num_cells is not None:
item = torch.full((num_cells, ), i, dtype=torch.long,
device=device)
batch.batch.append(item)
batch.ptr.append(batch.ptr[-1] + num_cells)
# Fix initial slice values:
for key in keys:
slices[key][0] = slices[key][1] - slices[key][1]
batch.batch = None if len(batch.batch) == 0 else batch.batch
batch.ptr = None if len(batch.ptr) == 1 else batch.ptr
batch.__slices__ = slices
batch.__cumsum__ = cumsum
batch.__cat_dims__ = cat_dims
batch.__num_cells_list__ = num_cells_list
batch.__num_cells_up_list__ = num_cells_up_list
batch.__num_cells_down_list__ = num_cells_down_list
ref_data = data_list[0]
for key in batch.keys:
items = batch[key]
item = items[0]
if isinstance(item, Tensor):
batch[key] = torch.cat(items, ref_data.__cat_dim__(key, item))
elif isinstance(item, SparseTensor):
batch[key] = torch.cat(items, ref_data.__cat_dim__(key, item))
elif isinstance(item, (int, float)):
batch[key] = torch.tensor(items)
return batch.contiguous()
def __getitem__(self, idx):
if isinstance(idx, str):
return super(CochainBatch, self).__getitem__(idx)
elif isinstance(idx, int):
# TODO: is the 'get_example' method needed for now?
#return self.get_example(idx)
raise NotImplementedError
else:
# TODO: is the 'index_select' method needed for now?
# return self.index_select(idx)
raise NotImplementedError
def to_cochain_list(self) -> List[Cochain]:
r"""Reconstructs the list of :class:`torch_geometric.data.Data` objects
from the batch object.
The batch object must have been created via :meth:`from_data_list` in
order to be able to reconstruct the initial objects."""
# TODO: is the 'to_cochain_list' method needed for now?
#return [self.get_example(i) for i in range(self.num_cochains)]
raise NotImplementedError
@property
def num_cochains(self) -> int:
"""Returns the number of cochains in the batch."""
if self.__num_cochains__ is not None:
return self.__num_cochains__
return self.ptr.numel() + 1
class Complex(object):
"""Class representing a cochain complex or an attributed cellular complex.
Args:
cochains: A list of cochains forming the cochain complex
y: A tensor of shape (1,) containing a label for the complex for complex-level tasks.
dimension: The dimension of the complex.
"""
def __init__(self, *cochains: Cochain, y: torch.Tensor = None, dimension: int = None):
if len(cochains) == 0:
raise ValueError('At least one cochain is required.')
if dimension is None:
dimension = len(cochains) - 1
if len(cochains) < dimension + 1:
raise ValueError(f'Not enough cochains passed, '
f'expected {dimension + 1}, received {len(cochains)}')
self.dimension = dimension
self.cochains = {i: cochains[i] for i in range(dimension + 1)}
self.nodes = cochains[0]
self.edges = cochains[1] if dimension >= 1 else None
self.two_cells = cochains[2] if dimension >= 2 else None
self.y = y
self._consolidate()
return
def _consolidate(self):
for dim in range(self.dimension+1):
cochain = self.cochains[dim]
assert cochain.dim == dim
if dim < self.dimension:
upper_cochain = self.cochains[dim + 1]
num_cells_up = upper_cochain.num_cells
assert num_cells_up is not None
if 'num_cells_up' in cochain:
assert cochain.num_cells_up == num_cells_up
else:
cochain.num_cells_up = num_cells_up
if dim > 0:
lower_cochain = self.cochains[dim - 1]
num_cells_down = lower_cochain.num_cells
assert num_cells_down is not None
if 'num_cells_down' in cochain:
assert cochain.num_cells_down == num_cells_down
else:
cochain.num_cells_down = num_cells_down
def to(self, device, **kwargs):
"""Performs tensor dtype and/or device conversion to cochains and label y, if set."""
# TODO: handle device conversion for specific attributes via `*keys` parameter
for dim in range(self.dimension + 1):
self.cochains[dim] = self.cochains[dim].to(device, **kwargs)
if self.y is not None:
self.y = self.y.to(device, **kwargs)
return self
def get_cochain_params(self,
dim : int,
max_dim : int=2,
include_top_features=True,
include_down_features=True,
include_boundary_features=True) -> CochainMessagePassingParams:
"""
Conveniently constructs all necessary input parameters to perform higher-dim
message passing on the cochain of specified `dim`.
Args:
dim: The dimension from which to extract the parameters
max_dim: The maximum dimension of interest.
This is only used in conjunction with include_top_features.
include_top_features: Whether to include the top features from level max_dim+1.
include_down_features: Include the features for down adjacency
include_boundary_features: Include the features for the boundary
Returns:
An object of type CochainMessagePassingParams
"""
if dim in self.cochains:
cells = self.cochains[dim]
x = cells.x
# Add up features
upper_index, upper_features = None, None
# We also check that dim+1 does exist in the current complex. This cochain might have been
# extracted from a higher dimensional complex by a batching operation, and dim+1
# might not exist anymore even though cells.upper_index is present.
if cells.upper_index is not None and (dim+1) in self.cochains:
upper_index = cells.upper_index
if self.cochains[dim + 1].x is not None and (dim < max_dim or include_top_features):
upper_features = torch.index_select(self.cochains[dim + 1].x, 0,
self.cochains[dim].shared_coboundaries)
# Add down features
lower_index, lower_features = None, None
if include_down_features and cells.lower_index is not None:
lower_index = cells.lower_index
if dim > 0 and self.cochains[dim - 1].x is not None:
lower_features = torch.index_select(self.cochains[dim - 1].x, 0,
self.cochains[dim].shared_boundaries)
# Add boundary features
boundary_index, boundary_features = None, None
if include_boundary_features and cells.boundary_index is not None:
boundary_index = cells.boundary_index
if dim > 0 and self.cochains[dim - 1].x is not None:
boundary_features = self.cochains[dim - 1].x
inputs = CochainMessagePassingParams(x, upper_index, lower_index,
up_attr=upper_features, down_attr=lower_features,
boundary_attr=boundary_features, boundary_index=boundary_index)
else:
raise NotImplementedError(
'Dim {} is not present in the complex or not yet supported.'.format(dim))
return inputs
def get_all_cochain_params(self,
max_dim:int=2,
include_top_features=True,
include_down_features=True,
include_boundary_features=True) -> List[CochainMessagePassingParams]:
"""Extracts the cochain parameters for message passing on the cochains up to max_dim.
Args:
max_dim: The maximum dimension of the complex for which to extract the parameters.
include_top_features: Whether to include the features from level max_dim+1.
include_down_features: Include the features for down adjacent cells.
include_boundary_features: Include the features for the boundary cells.
Returns:
A list of elements of type CochainMessagePassingParams.
"""
all_params = []
return_dim = min(max_dim, self.dimension)
for dim in range(return_dim+1):
all_params.append(self.get_cochain_params(dim, max_dim=max_dim,
include_top_features=include_top_features,
include_down_features=include_down_features,
include_boundary_features=include_boundary_features))
return all_params
def get_labels(self, dim=None):
"""Returns target labels.
If `dim`==k (integer in [0, self.dimension]) then the labels over k-cells are returned.
In the case `dim` is None the complex-wise label is returned.
"""
if dim is None:
y = self.y
else:
if dim in self.cochains:
y = self.cochains[dim].y
else:
raise NotImplementedError(
'Dim {} is not present in the complex or not yet supported.'.format(dim))
return y
def set_xs(self, xs: List[Tensor]):
"""Sets the features of the cochains to the values in the list"""
assert (self.dimension + 1) >= len(xs)
for i, x in enumerate(xs):
self.cochains[i].x = x
@property
def keys(self):
"""Returns all names of complex attributes."""
keys = [key for key in self.__dict__.keys() if self[key] is not None]
keys = [key for key in keys if key[:2] != '__' and key[-2:] != '__']
return keys
def __getitem__(self, key):
"""Gets the data of the attribute :obj:`key`."""
return getattr(self, key, None)
def __setitem__(self, key, value):
"""Sets the attribute :obj:`key` to :obj:`value`."""
setattr(self, key, value)
def __contains__(self, key):
"""Returns :obj:`True`, if the attribute :obj:`key` is present in the data."""
return key in self.keys
class ComplexBatch(Complex):
"""Class representing a batch of cochain complexes.
This is stored as a single cochain complex formed of batched cochains.
Args:
cochains: A list of cochain batches that will be put together in a complex batch
dimension: The dimension of the resulting complex.
y: A tensor of labels for the complexes in the batch.
num_complexes: The number of complexes in the batch.
"""
def __init__(self,
*cochains: CochainBatch,
dimension: int,
y: torch.Tensor = None,
num_complexes: int = None):
super(ComplexBatch, self).__init__(*cochains, y=y)
self.num_complexes = num_complexes
self.dimension = dimension
@classmethod
def from_complex_list(cls, data_list: List[Complex], follow_batch=[], max_dim: int = 2):
"""Constructs a ComplexBatch from a list of complexes.
Args:
data_list: a list of complexes from which the batch is built.
follow_batch: creates assignment batch vectors for each key in
:obj:`follow_batch`.
max_dim: the maximum cochain dimension considered when constructing the batch.
Returns:
A ComplexBatch object.
"""
dimension = max([data.dimension for data in data_list])
dimension = min(dimension, max_dim)
cochains = [list() for _ in range(dimension + 1)]
label_list = list()
per_complex_labels = True
for comp in data_list:
for dim in range(dimension+1):
if dim not in comp.cochains:
# If a dim-cochain is not present for the current complex, we instantiate one.
cochains[dim].append(Cochain(dim=dim))
if dim-1 in comp.cochains:
# If the cochain below exists in the complex, we need to add the number of
# boundaries to the newly initialised complex, otherwise batching will not work.
cochains[dim][-1].num_cells_down = comp.cochains[dim - 1].num_cells
else:
cochains[dim].append(comp.cochains[dim])
per_complex_labels &= comp.y is not None
if per_complex_labels:
label_list.append(comp.y)
batched_cochains = [CochainBatch.from_cochain_list(cochain_list, follow_batch=follow_batch)
for cochain_list in cochains]
y = None if not per_complex_labels else torch.cat(label_list, 0)
batch = cls(*batched_cochains, y=y, num_complexes=len(data_list), dimension=dimension)
return batch
| 30,723 | 41.145405 | 110 | py |
cwn | cwn-main/data/test_parallel.py | import pytest
from data.dummy_complexes import get_mol_testing_complex_list, convert_to_graph
from data.utils import convert_graph_dataset_with_rings
from data.test_dataset import compare_complexes
@pytest.mark.slow
def test_parallel_conversion_returns_same_order():
complexes = get_mol_testing_complex_list()
graphs = [convert_to_graph(comp) for comp in complexes]
seq_complexes, _, _ = convert_graph_dataset_with_rings(graphs, init_rings=True, n_jobs=1)
par_complexes, _, _ = convert_graph_dataset_with_rings(graphs, init_rings=True, n_jobs=2)
for comp_a, comp_b in zip(seq_complexes, par_complexes):
compare_complexes(comp_a, comp_b, True)
| 686 | 35.157895 | 93 | py |
cwn | cwn-main/data/test_tu_utils.py | import pytest
import os
import numpy as np
import torch
import random
from data.tu_utils import get_fold_indices, load_data, S2V_to_PyG
from torch_geometric.utils import degree
from definitions import ROOT_DIR
@pytest.fixture
def imdbbinary_graphs():
data, num_classes = load_data(os.path.join(ROOT_DIR, 'datasets', 'IMDBBINARY', 'raw'), 'IMDBBINARY', True)
graph_list = [S2V_to_PyG(datum) for datum in data]
return graph_list
@pytest.fixture
def imdbbinary_nonattributed_graphs():
data, num_classes = load_data(os.path.join(ROOT_DIR, 'datasets', 'IMDBBINARY', 'raw'), 'IMDBBINARY', False)
graph_list = [S2V_to_PyG(datum) for datum in data]
return graph_list
@pytest.fixture
def proteins_graphs():
data, num_classes = load_data(os.path.join(ROOT_DIR, 'datasets', 'PROTEINS', 'raw'), 'PROTEINS', True)
graph_list = [S2V_to_PyG(datum) for datum in data]
return graph_list
def validate_degree_as_tag(graphs):
degree_set = set()
degrees = dict()
for g, graph in enumerate(graphs):
d = degree(graph.edge_index[0])
d = d.numpy().astype(int).tolist()
degree_set |= set(d)
degrees[g] = d
encoder = {deg: d for d, deg in enumerate(sorted(degree_set))}
for g, graph in enumerate(graphs):
feats = graph.x
edge_index = graph.edge_index
assert feats.shape[1] == len(encoder)
row_sum = torch.sum(feats, 1)
assert torch.equal(row_sum, torch.ones(feats.shape[0]))
tags = torch.argmax(feats, 1)
d = degrees[g]
encoded = torch.LongTensor([encoder[deg] for deg in d])
assert torch.equal(tags, encoded), '{}\n{}'.format(tags, encoded)
def validate_get_fold_indices(graphs):
seeds = [0, 42, 43, 666]
folds = list(range(10))
prev_train = None
prev_test = None
for fold in folds:
for seed in seeds:
torch.manual_seed(43)
np.random.seed(43)
random.seed(43)
train_idx_0, test_idx_0 = get_fold_indices(graphs, seed, fold)
torch.manual_seed(0)
np.random.seed(0)
random.seed(0)
train_idx_1, test_idx_1 = get_fold_indices(graphs, seed, fold)
# check the splitting procedure is deterministic and robust w.r.t. global seeds
assert np.all(np.equal(train_idx_0, train_idx_1))
assert np.all(np.equal(test_idx_0, test_idx_1))
# check test and train form a partition
assert len(set(train_idx_0) & set(test_idx_0)) == 0
assert len(set(train_idx_0) | set(test_idx_0)) == len(graphs)
# check idxs are different across seeds
if prev_train is not None:
assert np.any(~np.equal(train_idx_0, prev_train))
assert np.any(~np.equal(test_idx_0, prev_test))
prev_train = train_idx_0
prev_test = test_idx_0
def validate_constant_scalar_features(graphs):
for graph in graphs:
feats = graph.x
assert feats.shape[1]
expected = torch.ones(feats.shape[0], 1)
assert torch.equal(feats, expected)
@pytest.mark.data
def test_get_fold_indices_on_imdbbinary(imdbbinary_graphs):
validate_get_fold_indices(imdbbinary_graphs)
@pytest.mark.data
def test_degree_as_tag_on_imdbbinary(imdbbinary_graphs):
validate_degree_as_tag(imdbbinary_graphs)
@pytest.mark.data
def test_constant_scalar_features_on_imdbbinary_without_tags(imdbbinary_nonattributed_graphs):
validate_constant_scalar_features(imdbbinary_nonattributed_graphs)
@pytest.mark.data
def test_degree_as_tag_on_proteins(proteins_graphs):
validate_degree_as_tag(proteins_graphs)
| 3,720 | 32.827273 | 111 | py |
cwn | cwn-main/data/test_batching.py | import torch
import pytest
import itertools
from data.dummy_complexes import (get_house_complex, get_square_complex, get_pyramid_complex,
get_square_dot_complex, get_kite_complex)
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from data.data_loading import DataLoader, load_dataset
def validate_double_house(batch):
expected_node_upper = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4, 5, 6, 5, 8, 6, 7, 7, 8, 7, 9, 8, 9],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3, 6, 5, 8, 5, 7, 6, 8, 7, 9, 7, 9, 8]], dtype=torch.long)
expected_node_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 5, 5, 4, 4, 6, 6, 9, 9, 7, 7, 8, 8, 11, 11, 10, 10], dtype=torch.long)
expected_node_x = torch.tensor([[1], [2], [3], [4], [5], [1], [2], [3], [4], [5]], dtype=torch.float)
expected_node_y = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_node_batch = torch.tensor([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_upper = torch.tensor([[2, 4, 2, 5, 4, 5, 8, 10, 8, 11, 10, 11],
[4, 2, 5, 2, 5, 4, 10, 8, 11, 8, 11, 10]], dtype=torch.long)
expected_edge_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_lower = torch.tensor([[0, 1, 0, 3, 1, 2, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 4, 5, 6, 7, 6, 9, 7, 8, 7, 11, 8, 9, 8, 10, 8, 11, 9, 10, 10, 11],
[1, 0, 3, 0, 2, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 4, 7, 6, 9, 6, 8, 7, 11, 7, 9, 8, 10, 8, 11, 8, 10, 9, 11, 10]],
dtype=torch.long)
expected_edge_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 4, 4, 6, 6, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9],
dtype=torch.long)
expected_edge_x = torch.tensor([[1], [2], [3], [4], [5], [6], [1], [2], [3], [4], [5], [6]], dtype=torch.float)
expected_edge_y = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_batch = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_two_cell_x = torch.tensor([[1], [1]], dtype=torch.float)
expected_two_cell_y = torch.tensor([2, 2], dtype=torch.long)
expected_two_cell_batch = torch.tensor([0, 1], dtype=torch.long)
assert torch.equal(expected_node_upper, batch.nodes.upper_index)
assert torch.equal(expected_node_shared_coboundaries, batch.nodes.shared_coboundaries)
assert batch.nodes.lower_index is None
assert batch.nodes.shared_boundaries is None
assert torch.equal(expected_node_x, batch.nodes.x)
assert torch.equal(expected_node_y, batch.nodes.y)
assert torch.equal(expected_node_batch, batch.nodes.batch)
assert torch.equal(expected_edge_upper, batch.edges.upper_index)
assert torch.equal(expected_edge_shared_coboundaries, batch.edges.shared_coboundaries)
assert torch.equal(expected_edge_lower, batch.edges.lower_index)
assert torch.equal(expected_edge_shared_boundaries, batch.edges.shared_boundaries)
assert torch.equal(expected_edge_x, batch.edges.x)
assert torch.equal(expected_edge_y, batch.edges.y)
assert torch.equal(expected_edge_batch, batch.edges.batch)
assert batch.two_cells.upper_index is None
assert batch.two_cells.lower_index is None
assert batch.two_cells.shared_coboundaries is None
assert batch.two_cells.shared_boundaries is None
assert torch.equal(expected_two_cell_x, batch.two_cells.x)
assert torch.equal(expected_two_cell_y, batch.two_cells.y)
assert torch.equal(expected_two_cell_batch, batch.two_cells.batch)
def validate_square_dot_and_square(batch):
expected_node_upper = torch.tensor([ [0, 1, 0, 3, 1, 2, 2, 3, 5, 6, 5, 8, 6, 7, 7, 8],
[1, 0, 3, 0, 2, 1, 3, 2, 6, 5, 8, 5, 7, 6, 8, 7]], dtype=torch.long)
expected_node_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 4, 4, 7, 7, 5, 5, 6, 6], dtype=torch.long)
expected_node_x = torch.tensor([[1], [2], [3], [4], [5], [1], [2], [3], [4]], dtype=torch.float)
expected_node_y = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_node_batch = torch.tensor([0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=torch.long)
expected_edge_lower = torch.tensor([ [0, 1, 0, 3, 1, 2, 2, 3, 4, 5, 4, 7, 5, 6, 6, 7],
[1, 0, 3, 0, 2, 1, 3, 2, 5, 4, 7, 4, 6, 5, 7, 6]], dtype=torch.long)
expected_edge_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 3, 3, 6, 6, 5, 5, 7, 7, 8, 8],
dtype=torch.long)
expected_edge_x = torch.tensor([[1], [2], [3], [4], [1], [2], [3], [4]], dtype=torch.float)
expected_edge_y = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1,], dtype=torch.long)
expected_edge_batch = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1], dtype=torch.long)
assert torch.equal(expected_node_upper, batch.nodes.upper_index)
assert torch.equal(expected_node_shared_coboundaries, batch.nodes.shared_coboundaries)
assert batch.nodes.lower_index is None
assert batch.nodes.shared_boundaries is None
assert torch.equal(expected_node_x, batch.nodes.x)
assert torch.equal(expected_node_y, batch.nodes.y)
assert torch.equal(expected_node_batch, batch.nodes.batch)
assert batch.edges.upper_index is None
assert batch.edges.shared_coboundaries is None
assert torch.equal(expected_edge_lower, batch.edges.lower_index)
assert torch.equal(expected_edge_shared_boundaries, batch.edges.shared_boundaries)
assert torch.equal(expected_edge_x, batch.edges.x)
assert torch.equal(expected_edge_y, batch.edges.y)
assert torch.equal(expected_edge_batch, batch.edges.batch)
def validate_kite_and_house(batch):
kite_node_upper = torch.tensor([[0, 1, 0, 2, 1, 2, 1, 3, 2, 3, 3, 4],
[1, 0, 2, 0, 2, 1, 3, 1, 3, 2, 4, 3]], dtype=torch.long)
shifted_house_node_upper = 5 + torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3]], dtype=torch.long)
expected_node_upper = torch.cat([kite_node_upper, shifted_house_node_upper], 1)
kite_node_shared_coboundaries = torch.tensor([0, 0, 2, 2, 1, 1, 3, 3, 4, 4, 5, 5], dtype=torch.long)
shifted_house_node_shared_coboundaries = 6 + torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 5, 5, 4, 4], dtype=torch.long)
expected_node_shared_coboundaries = torch.cat([kite_node_shared_coboundaries, shifted_house_node_shared_coboundaries], 0)
expected_node_x = torch.tensor([[1], [2], [3], [4], [5], [1], [2], [3], [4], [5]], dtype=torch.float)
expected_node_y = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_node_batch = torch.tensor([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype=torch.long)
kite_edge_upper = torch.tensor([[0, 1, 0, 2, 1, 2, 1, 3, 1, 4, 3, 4],
[1, 0, 2, 0, 2, 1, 3, 1, 4, 1, 4, 3]], dtype=torch.long)
shifted_house_edge_upper = 6 + torch.tensor([[2, 4, 2, 5, 4, 5],
[4, 2, 5, 2, 5, 4]], dtype=torch.long)
expected_edge_upper = torch.cat([kite_edge_upper, shifted_house_edge_upper], 1)
kite_edge_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=torch.long)
shifted_house_edge_shared_coboundaries = 2 + torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_edge_shared_coboundaries = torch.cat([kite_edge_shared_coboundaries, shifted_house_edge_shared_coboundaries], 0)
kite_edge_lower = torch.tensor([ [0, 1, 0, 3, 1, 3, 0, 2, 1, 2, 2, 4, 1, 4, 3, 4, 3, 5, 4, 5],
[1, 0, 3, 0, 3, 1, 2, 0, 2, 1, 4, 2, 4, 1, 4, 3, 5, 3, 5, 4]], dtype=torch.long)
shifted_house_lower = 6 + torch.tensor([[0, 1, 0, 3, 1, 2, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 4, 5],
[1, 0, 3, 0, 2, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 4]], dtype=torch.long)
expected_edge_lower = torch.cat([kite_edge_lower, shifted_house_lower], 1)
kite_edge_shared_boundaries = torch.tensor([1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3], dtype=torch.long)
shifted_house_edge_shared_boundaries = 5 + torch.tensor([1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 4, 4], dtype=torch.long)
expected_edge_shared_boundaries = torch.cat([kite_edge_shared_boundaries, shifted_house_edge_shared_boundaries], 0)
expected_edge_x = torch.tensor([[1], [2], [3], [4], [5], [6], [1], [2], [3], [4], [5], [6]], dtype=torch.float)
expected_edge_y = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_batch = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_two_cell_lower = torch.tensor([[0, 1],
[1, 0]], dtype=torch.long)
expected_two_cell_shared_boundaries = torch.tensor([1, 1], dtype=torch.long)
expected_two_cell_x = torch.tensor([[1], [2], [1]], dtype=torch.float)
expected_two_cell_y = torch.tensor([2, 2, 2], dtype=torch.long)
expected_two_cell_batch = torch.tensor([0, 0, 1], dtype=torch.long)
assert torch.equal(expected_node_upper, batch.nodes.upper_index)
assert torch.equal(expected_node_shared_coboundaries, batch.nodes.shared_coboundaries)
assert batch.nodes.lower_index is None
assert batch.nodes.shared_boundaries is None
assert torch.equal(expected_node_x, batch.nodes.x)
assert torch.equal(expected_node_y, batch.nodes.y)
assert torch.equal(expected_node_batch, batch.nodes.batch)
assert torch.equal(expected_edge_upper, batch.edges.upper_index)
assert torch.equal(expected_edge_shared_coboundaries, batch.edges.shared_coboundaries)
assert torch.equal(expected_edge_lower, batch.edges.lower_index)
assert torch.equal(expected_edge_shared_boundaries, batch.edges.shared_boundaries)
assert torch.equal(expected_edge_x, batch.edges.x)
assert torch.equal(expected_edge_y, batch.edges.y)
assert torch.equal(expected_edge_batch, batch.edges.batch)
assert batch.two_cells.upper_index is None
assert batch.two_cells.shared_coboundaries is None
assert torch.equal(expected_two_cell_lower, batch.two_cells.lower_index)
assert torch.equal(expected_two_cell_shared_boundaries, batch.two_cells.shared_boundaries)
assert torch.equal(expected_two_cell_x, batch.two_cells.x)
assert torch.equal(expected_two_cell_y, batch.two_cells.y)
assert torch.equal(expected_two_cell_batch, batch.two_cells.batch)
def validate_house_and_square(batch):
expected_node_upper = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4, 5, 6, 5, 8, 6, 7, 7, 8],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3, 6, 5, 8, 5, 7, 6, 8, 7]], dtype=torch.long)
expected_node_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 5, 5, 4, 4, 6, 6, 9, 9, 7, 7, 8, 8], dtype=torch.long)
expected_node_x = torch.tensor([[1], [2], [3], [4], [5], [1], [2], [3], [4]], dtype=torch.float)
expected_node_y = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_node_batch = torch.tensor([0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=torch.long)
expected_edge_upper = torch.tensor([[2, 4, 2, 5, 4, 5],
[4, 2, 5, 2, 5, 4]], dtype=torch.long)
expected_edge_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_edge_lower = torch.tensor([ [0, 1, 0, 3, 1, 2, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 4, 5, 6, 7, 6, 9, 7, 8, 8, 9],
[1, 0, 3, 0, 2, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 4, 7, 6, 9, 6, 8, 7, 9, 8]],
dtype=torch.long)
expected_edge_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 4, 4, 6, 6, 5, 5, 7, 7, 8, 8],
dtype=torch.long)
expected_edge_x = torch.tensor([[1], [2], [3], [4], [5], [6], [1], [2], [3], [4]], dtype=torch.float)
expected_edge_y = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], dtype=torch.long)
expected_edge_batch = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=torch.long)
expected_two_cell_x = torch.tensor([[1]], dtype=torch.float)
expected_two_cell_y = torch.tensor([2], dtype=torch.long)
expected_two_cell_batch = torch.tensor([0], dtype=torch.long)
assert torch.equal(expected_node_upper, batch.nodes.upper_index)
assert torch.equal(expected_node_shared_coboundaries, batch.nodes.shared_coboundaries)
assert batch.nodes.lower_index is None
assert batch.nodes.shared_boundaries is None
assert torch.equal(expected_node_x, batch.nodes.x)
assert torch.equal(expected_node_y, batch.nodes.y)
assert torch.equal(expected_node_batch, batch.nodes.batch)
assert torch.equal(expected_edge_upper, batch.edges.upper_index)
assert torch.equal(expected_edge_shared_coboundaries, batch.edges.shared_coboundaries)
assert torch.equal(expected_edge_lower, batch.edges.lower_index)
assert torch.equal(expected_edge_shared_boundaries, batch.edges.shared_boundaries)
assert torch.equal(expected_edge_x, batch.edges.x)
assert torch.equal(expected_edge_y, batch.edges.y)
assert torch.equal(expected_edge_batch, batch.edges.batch)
assert batch.two_cells.upper_index is None
assert batch.two_cells.lower_index is None
assert batch.two_cells.shared_coboundaries is None
assert batch.two_cells.shared_boundaries is None
assert torch.equal(expected_two_cell_x, batch.two_cells.x)
assert torch.equal(expected_two_cell_y, batch.two_cells.y)
assert torch.equal(expected_two_cell_batch, batch.two_cells.batch)
def validate_house_square_house(batch):
expected_node_upper = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4, 5, 6, 5, 8, 6, 7, 7, 8, 9, 10, 9, 12, 10, 11, 11, 12, 11, 13, 12, 13],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3, 6, 5, 8, 5, 7, 6, 8, 7, 10, 9, 12, 9, 11, 10, 12, 11, 13, 11, 13, 12]],
dtype=torch.long)
expected_node_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 5, 5, 4, 4, 6, 6, 9, 9, 7, 7, 8, 8, 10, 10, 13, 13, 11, 11, 12, 12, 15, 15, 14, 14],
dtype=torch.long)
expected_node_x = torch.tensor([[1], [2], [3], [4], [5], [1], [2], [3], [4], [1], [2], [3], [4], [5]], dtype=torch.float)
expected_node_y = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_node_batch = torch.tensor([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2], dtype=torch.long)
expected_edge_upper = torch.tensor([[2, 4, 2, 5, 4, 5, 12, 14, 12, 15, 14, 15],
[4, 2, 5, 2, 5, 4, 14, 12, 15, 12, 15, 14]], dtype=torch.long)
expected_edge_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_lower = torch.tensor([ [0, 1, 0, 3, 1, 2, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 4, 5, 6, 7, 6, 9, 7, 8, 8, 9, 10, 11, 10, 13, 11, 12, 11, 15, 12, 13, 12, 14, 12, 15, 13, 14, 14, 15],
[1, 0, 3, 0, 2, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 4, 7, 6, 9, 6, 8, 7, 9, 8, 11, 10, 13, 10, 12, 11, 15, 11, 13, 12, 14, 12, 15, 12, 14, 13, 15, 14]],
dtype=torch.long)
expected_edge_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 4, 4, 6, 6, 5, 5, 7, 7, 8, 8, 10, 10, 9, 9, 11, 11, 11, 11, 12, 12, 12, 12, 11, 11, 12, 12, 13, 13],
dtype=torch.long)
expected_edge_x = torch.tensor([[1], [2], [3], [4], [5], [6], [1], [2], [3], [4], [1], [2], [3], [4], [5], [6]], dtype=torch.float)
expected_edge_y = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_batch = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=torch.long)
expected_two_cell_x = torch.tensor([[1], [1]], dtype=torch.float)
expected_two_cell_y = torch.tensor([2, 2], dtype=torch.long)
expected_two_cell_batch = torch.tensor([0, 2], dtype=torch.long)
assert torch.equal(expected_node_upper, batch.nodes.upper_index)
assert torch.equal(expected_node_shared_coboundaries, batch.nodes.shared_coboundaries)
assert batch.nodes.lower_index is None
assert batch.nodes.shared_boundaries is None
assert torch.equal(expected_node_x, batch.nodes.x)
assert torch.equal(expected_node_y, batch.nodes.y)
assert torch.equal(expected_node_batch, batch.nodes.batch)
assert torch.equal(expected_edge_upper, batch.edges.upper_index)
assert torch.equal(expected_edge_shared_coboundaries, batch.edges.shared_coboundaries)
assert torch.equal(expected_edge_lower, batch.edges.lower_index)
assert torch.equal(expected_edge_shared_boundaries, batch.edges.shared_boundaries)
assert torch.equal(expected_edge_x, batch.edges.x)
assert torch.equal(expected_edge_y, batch.edges.y)
assert torch.equal(expected_edge_batch, batch.edges.batch)
assert batch.two_cells.upper_index is None
assert batch.two_cells.lower_index is None
assert batch.two_cells.shared_coboundaries is None
assert batch.two_cells.shared_boundaries is None
assert torch.equal(expected_two_cell_x, batch.two_cells.x)
assert torch.equal(expected_two_cell_y, batch.two_cells.y)
assert torch.equal(expected_two_cell_batch, batch.two_cells.batch)
def validate_house_no_batching(batch):
expected_node_upper = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3]], dtype=torch.long)
expected_node_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 5, 5, 4, 4], dtype=torch.long)
expected_node_x = torch.tensor([[1], [2], [3], [4], [5]], dtype=torch.float)
expected_node_y = torch.tensor([0, 0, 0, 0, 0], dtype=torch.long)
expected_node_batch = torch.tensor([0, 0, 0, 0, 0], dtype=torch.long)
expected_edge_upper = torch.tensor([[2, 4, 2, 5, 4, 5],
[4, 2, 5, 2, 5, 4]], dtype=torch.long)
expected_edge_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_edge_lower = torch.tensor([[0, 1, 0, 3, 1, 2, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 4, 5],
[1, 0, 3, 0, 2, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 4]],
dtype=torch.long)
expected_edge_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 4, 4],
dtype=torch.long)
expected_edge_x = torch.tensor([[1], [2], [3], [4], [5], [6]], dtype=torch.float)
expected_edge_y = torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.long)
expected_edge_batch = torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long)
expected_two_cell_x = torch.tensor([[1]], dtype=torch.float)
expected_two_cell_y = torch.tensor([2], dtype=torch.long)
expected_two_cell_batch = torch.tensor([0], dtype=torch.long)
assert torch.equal(expected_node_upper, batch.nodes.upper_index)
assert torch.equal(expected_node_shared_coboundaries, batch.nodes.shared_coboundaries)
assert batch.nodes.lower_index is None
assert batch.nodes.shared_boundaries is None
assert torch.equal(expected_node_x, batch.nodes.x)
assert torch.equal(expected_node_y, batch.nodes.y)
assert torch.equal(expected_node_batch, batch.nodes.batch)
assert torch.equal(expected_edge_upper, batch.edges.upper_index)
assert torch.equal(expected_edge_shared_coboundaries, batch.edges.shared_coboundaries)
assert torch.equal(expected_edge_lower, batch.edges.lower_index)
assert torch.equal(expected_edge_shared_boundaries, batch.edges.shared_boundaries)
assert torch.equal(expected_edge_x, batch.edges.x)
assert torch.equal(expected_edge_y, batch.edges.y)
assert torch.equal(expected_edge_batch, batch.edges.batch)
assert batch.two_cells.upper_index is None
assert batch.two_cells.lower_index is None
assert batch.two_cells.shared_coboundaries is None
assert batch.two_cells.shared_boundaries is None
assert torch.equal(expected_two_cell_x, batch.two_cells.x)
assert torch.equal(expected_two_cell_y, batch.two_cells.y)
assert torch.equal(expected_two_cell_batch, batch.two_cells.batch)
def test_double_house_batching():
"""
4 9
/ \ / \
3---2 8---7
| | | |
0---1 5---6
. .
4 5 10 11
. 2 . . 8 .
3 1 9 7
. 0 . . 6 .
. .
/0\ /1\
.---. .---.
| | | |
.---. .---.
"""
house_1 = get_house_complex()
house_2 = get_house_complex()
complex_list = [house_1, house_2]
batch = ComplexBatch.from_complex_list(complex_list)
validate_double_house(batch)
def test_house_and_square_batching():
"""
4
/ \
3---2 8---7
| | | |
0---1 5---6
.
4 5
. 2 . . 8 .
3 1 9 7
. 0 . . 6 .
.
/0\
.---. .---.
| | | |
.---. .---.
"""
house_1 = get_house_complex()
square = get_square_complex()
complex_list = [house_1, square]
batch = ComplexBatch.from_complex_list(complex_list)
validate_house_and_square(batch)
def test_house_square_house_batching():
"""
4 13
/ \ / \
3---2 8---7 12--11
| | | | | |
0---1 5---6 9---10
. .
4 5 14 15
. 2 . . 8 . . 12.
3 1 9 7 13 11
. 0 . . 6 . . 10 .
. .
/0\ /1\
.---. .---. .---.
| | | | | |
.---. .---. .---.
"""
house_1 = get_house_complex()
house_2 = get_house_complex()
square = get_square_complex()
complex_list = [house_1, square, house_2]
batch = ComplexBatch.from_complex_list(complex_list)
validate_house_square_house(batch)
def test_square_dot_square_batching():
'''
3---2 8---7
| | | |
0---1 4 5---6
. 2 . . 6 .
3 1 7 5
. 0 . . . 4 .
.---. .---.
| | | |
.---. . .---.
'''
square_dot = get_square_dot_complex()
square = get_square_complex()
complex_list = [square_dot, square]
batch = ComplexBatch.from_complex_list(complex_list)
validate_square_dot_and_square(batch)
def test_kite_house_batching():
'''
2---3---4 9
/ \ / / \
0---1 8---7
| |
5---6
. 4 . 5 . .
2 1 3 10 11
. 0 . . 8 .
9 7
. 6 .
.---.---. .
/0\1/ /2\
.---. .---.
| |
.---.
'''
kite = get_kite_complex()
house = get_house_complex()
complex_list = [kite, house]
batch = ComplexBatch.from_complex_list(complex_list)
validate_kite_and_house(batch)
def test_data_loader():
data_list_1 = [
get_house_complex(),
get_house_complex(),
get_house_complex(),
get_square_complex()]
data_list_2 = [
get_house_complex(),
get_square_complex(),
get_house_complex(),
get_house_complex()]
data_list_3 = [
get_house_complex(),
get_square_complex(),
get_pyramid_complex(),
get_pyramid_complex()]
data_list_4 = [
get_square_dot_complex(),
get_square_complex(),
get_kite_complex(),
get_house_complex(),
get_house_complex()]
data_loader_1 = DataLoader(data_list_1, batch_size=2)
data_loader_2 = DataLoader(data_list_2, batch_size=3)
data_loader_3 = DataLoader(data_list_3, batch_size=3, max_dim=3)
data_loader_4 = DataLoader(data_list_4, batch_size=2)
count = 0
for batch in data_loader_1:
count += 1
if count == 1:
validate_double_house(batch)
elif count == 2:
validate_house_and_square(batch)
assert count == 2
count = 0
for batch in data_loader_2:
count += 1
if count == 1:
validate_house_square_house(batch)
elif count == 2:
validate_house_no_batching(batch)
assert count == 2
count = 0
for batch in data_loader_3:
count += 1
assert count == 2
count = 0
for batch in data_loader_4:
count += 1
if count == 1:
validate_square_dot_and_square(batch)
elif count == 2:
validate_kite_and_house(batch)
else:
validate_house_no_batching(batch)
assert count == 3
def test_set_for_features_in_batch():
house_1 = get_house_complex()
house_2 = get_house_complex()
square = get_square_complex()
complex_list = [house_1, square, house_2]
vx = torch.arange(21, 35, dtype=torch.float).view(14, 1)
ex = torch.arange(21, 37, dtype=torch.float).view(16, 1)
tx = torch.arange(21, 23, dtype=torch.float).view(2, 1)
xs = [vx, ex, tx]
batch = ComplexBatch.from_complex_list(complex_list)
batch.set_xs(xs)
assert torch.equal(batch.cochains[0].x, vx)
assert torch.equal(batch.cochains[1].x, ex)
assert torch.equal(batch.cochains[2].x, tx)
def test_set_xs_does_not_mutate_dataset():
"""Batches should be copied, so these mutations should not change the dataset"""
data_list = get_testing_complex_list()
data_loader = DataLoader(data_list, batch_size=5, max_dim=2)
# Save batch contents
xs = [[] for _ in range(4)] # we consider up to dim 3 due to the presence of pyramids
for batch in data_loader:
for i in range(batch.dimension + 1):
xs[i].append(batch.cochains[i].x)
txs = []
for i in range(4):
txs.append(torch.cat(xs[i], dim=0) if len(xs[i]) > 0 else None)
# Set batch features
for batch in data_loader:
new_xs = []
for i in range(batch.dimension + 1):
new_xs.append(torch.zeros_like(batch.cochains[i].x))
batch.set_xs(new_xs)
# Save batch contents after set_xs
xs_after = [[] for _ in range(4)]
for batch in data_loader:
for i in range(batch.dimension + 1):
xs_after[i].append(batch.cochains[i].x)
txs_after = []
for i in range(4):
txs_after.append(torch.cat(xs_after[i], dim=0) if len(xs_after[i]) > 0 else None)
# Check that the batch features are the same
for i in range(4):
if txs_after[i] is None:
assert txs[i] is None
else:
assert torch.equal(txs_after[i], txs[i])
def test_batching_returns_the_same_features():
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2, 3]
bs = list(range(2, 11))
params = itertools.product(bs, dims)
for batch_size, batch_max_dim, in params:
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
batched_x[dim].append(params[dim].x)
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
x = [[] for _ in range(batch_max_dim+1)]
for complex in data_list:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
x[dim].append(params[dim].x)
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert torch.equal(batched_xs[i], xs[i])
@pytest.mark.data
def test_batching_returns_the_same_features_on_proteins():
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
assert len(dataset) == 1113
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
batch_max_dim = 3
data_loader = DataLoader(dataset, batch_size=32, max_dim=batch_max_dim)
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
batched_x[dim].append(params[dim].x)
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
x = [[] for _ in range(batch_max_dim+1)]
for complex in dataset:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
x[dim].append(params[dim].x)
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert torch.equal(batched_xs[i], xs[i])
@pytest.mark.data
def test_batching_returns_the_same_features_on_ring_proteins():
dataset = load_dataset('PROTEINS', max_dim=2, fold=0, init_method='mean',
max_ring_size=7)
assert len(dataset) == 1113
assert dataset.max_dim == 2
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
batch_max_dim = 3
data_loader = DataLoader(dataset, batch_size=32, max_dim=batch_max_dim)
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
batched_x[dim].append(params[dim].x)
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
x = [[] for _ in range(batch_max_dim+1)]
for complex in dataset:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
x[dim].append(params[dim].x)
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert torch.equal(batched_xs[i], xs[i])
@pytest.mark.data
def test_batching_returns_the_same_up_attr_on_proteins():
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
assert len(dataset) == 1113
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
batch_max_dim = 3
data_loader = DataLoader(dataset, batch_size=32, max_dim=batch_max_dim)
# Batched
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
if params[dim].kwargs['up_attr'] is not None:
batched_x[dim].append(params[dim].kwargs['up_attr'])
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
# Un-batched
x = [[] for _ in range(batch_max_dim+1)]
for complex in dataset:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
# TODO: Modify test after merging the top_feature branch
# Right now, the last level cannot have top features
if params[dim].kwargs['up_attr'] is not None and dim < batch_max_dim:
x[dim].append(params[dim].kwargs['up_attr'])
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert torch.equal(xs[i], batched_xs[i])
def test_batching_returns_the_same_up_attr():
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2, 3]
bs = list(range(2, 11))
params = itertools.product(bs, dims)
for batch_size, batch_max_dim, in params:
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
# Batched
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
if params[dim].kwargs['up_attr'] is not None:
batched_x[dim].append(params[dim].kwargs['up_attr'])
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
# Un-batched
x = [[] for _ in range(batch_max_dim+1)]
for complex in data_list:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
# TODO: Modify test after merging the top_feature branch
# Right now, the last level cannot have top features
if params[dim].kwargs['up_attr'] is not None and dim < batch_max_dim:
x[dim].append(params[dim].kwargs['up_attr'])
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert torch.equal(xs[i], batched_xs[i])
@pytest.mark.data
def test_batching_returns_the_same_down_attr_on_proteins():
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
assert len(dataset) == 1113
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
batch_max_dim = 3
data_loader = DataLoader(dataset, batch_size=32, max_dim=batch_max_dim)
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
if params[dim].kwargs['down_attr'] is not None:
batched_x[dim].append(params[dim].kwargs['down_attr'])
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
# Un-batched
x = [[] for _ in range(batch_max_dim+1)]
for complex in dataset:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
if params[dim].kwargs['down_attr'] is not None:
x[dim].append(params[dim].kwargs['down_attr'])
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert len(xs[i]) == len(batched_xs[i])
assert torch.equal(xs[i], batched_xs[i])
def test_batching_returns_the_same_down_attr():
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2, 3]
bs = list(range(2, 11))
params = itertools.product(bs, dims)
for batch_size, batch_max_dim, in params:
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
batched_x = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
if params[dim].kwargs['down_attr'] is not None:
batched_x[dim].append(params[dim].kwargs['down_attr'])
batched_xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x[i]) > 0:
batched_xs[i] = torch.cat(batched_x[i], dim=0)
# Un-batched
x = [[] for _ in range(batch_max_dim+1)]
for complex in data_list:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
if params[dim].kwargs['down_attr'] is not None:
x[dim].append(params[dim].kwargs['down_attr'])
xs = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x[i]) > 0:
xs[i] = torch.cat(x[i], dim=0)
for i in range(batch_max_dim+1):
if xs[i] is None or batched_xs[i] is None:
assert xs[i] == batched_xs[i]
else:
assert len(xs[i]) == len(batched_xs[i])
assert torch.equal(xs[i], batched_xs[i])
@pytest.mark.data
def test_batching_of_boundary_index_on_proteins():
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
assert len(dataset) == 1113
split_idx = dataset.get_idx_split()
dataset = dataset[split_idx['valid']]
assert len(dataset) == 111
batch_max_dim = 3
data_loader = DataLoader(dataset, batch_size=32, max_dim=batch_max_dim)
batched_x_boundaries = [[] for _ in range(batch_max_dim+1)]
batched_x_cells = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
if params[dim].kwargs['boundary_attr'] is not None:
assert params[dim].boundary_index is not None
boundary_attrs = params[dim].kwargs['boundary_attr']
batched_x_boundaries[dim].append(
torch.index_select(boundary_attrs, 0, params[dim].boundary_index[0]))
batched_x_cells[dim].append(
torch.index_select(params[dim].x, 0, params[dim].boundary_index[1]))
batched_xs_boundaries = [None for _ in range(batch_max_dim+1)]
batched_xs_cells = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x_boundaries[i]) > 0:
batched_xs_boundaries[i] = torch.cat(batched_x_boundaries[i], dim=0)
if len(batched_x_cells[i]) > 0:
batched_xs_cells[i] = torch.cat(batched_x_cells[i], dim=0)
# Un-batched
x_boundaries = [[] for _ in range(batch_max_dim+1)]
x_cells = [[] for _ in range(batch_max_dim+1)]
for complex in dataset:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
if params[dim].kwargs['boundary_attr'] is not None:
assert params[dim].boundary_index is not None
boundary_attrs = params[dim].kwargs['boundary_attr']
x_boundaries[dim].append(
torch.index_select(boundary_attrs, 0, params[dim].boundary_index[0]))
x_cells[dim].append(
torch.index_select(params[dim].x, 0, params[dim].boundary_index[1]))
xs_boundaries = [None for _ in range(batch_max_dim+1)]
xs_cells = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x_boundaries[i]) > 0:
xs_boundaries[i] = torch.cat(x_boundaries[i], dim=0)
xs_cells[i] = torch.cat(x_cells[i], dim=0)
for i in range(batch_max_dim+1):
if xs_boundaries[i] is None or batched_xs_boundaries[i] is None:
assert xs_boundaries[i] == batched_xs_boundaries[i]
else:
assert len(xs_boundaries[i]) == len(batched_xs_boundaries[i])
assert torch.equal(xs_boundaries[i], batched_xs_boundaries[i])
if xs_cells[i] is None or batched_xs_cells[i] is None:
assert xs_cells[i] == batched_xs_cells[i]
else:
assert len(xs_cells[i]) == len(batched_xs_cells[i])
assert torch.equal(xs_cells[i], batched_xs_cells[i])
def test_batching_of_boundary_index():
data_list = get_testing_complex_list()
# Try multiple parameters
dims = [1, 2, 3]
bs = list(range(2, 11))
params = itertools.product(bs, dims)
for batch_size, batch_max_dim, in params:
data_loader = DataLoader(data_list, batch_size=batch_size, max_dim=batch_max_dim)
batched_x_boundaries = [[] for _ in range(batch_max_dim+1)]
batched_x_cells = [[] for _ in range(batch_max_dim+1)]
for batch in data_loader:
params = batch.get_all_cochain_params()
assert len(params) <= batch_max_dim+1
for dim in range(len(params)):
if params[dim].kwargs['boundary_attr'] is not None:
assert params[dim].boundary_index is not None
boundary_attrs = params[dim].kwargs['boundary_attr']
batched_x_boundaries[dim].append(
torch.index_select(boundary_attrs, 0, params[dim].boundary_index[0]))
batched_x_cells[dim].append(
torch.index_select(params[dim].x, 0, params[dim].boundary_index[1]))
batched_xs_boundaries = [None for _ in range(batch_max_dim+1)]
batched_xs_cells = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(batched_x_boundaries[i]) > 0:
batched_xs_boundaries[i] = torch.cat(batched_x_boundaries[i], dim=0)
if len(batched_x_cells[i]) > 0:
batched_xs_cells[i] = torch.cat(batched_x_cells[i], dim=0)
# Un-batched
x_boundaries = [[] for _ in range(batch_max_dim+1)]
x_cells = [[] for _ in range(batch_max_dim+1)]
for complex in data_list:
params = complex.get_all_cochain_params()
for dim in range(min(len(params), batch_max_dim+1)):
if params[dim].kwargs['boundary_attr'] is not None:
assert params[dim].boundary_index is not None
boundary_attrs = params[dim].kwargs['boundary_attr']
x_boundaries[dim].append(
torch.index_select(boundary_attrs, 0, params[dim].boundary_index[0]))
x_cells[dim].append(
torch.index_select(params[dim].x, 0, params[dim].boundary_index[1]))
xs_boundaries = [None for _ in range(batch_max_dim+1)]
xs_cells = [None for _ in range(batch_max_dim+1)]
for i in range(batch_max_dim+1):
if len(x_boundaries[i]) > 0:
xs_boundaries[i] = torch.cat(x_boundaries[i], dim=0)
xs_cells[i] = torch.cat(x_cells[i], dim=0)
for i in range(batch_max_dim+1):
if xs_boundaries[i] is None or batched_xs_boundaries[i] is None:
assert xs_boundaries[i] == batched_xs_boundaries[i]
else:
assert len(xs_boundaries[i]) == len(batched_xs_boundaries[i])
assert torch.equal(xs_boundaries[i], batched_xs_boundaries[i])
if xs_cells[i] is None or batched_xs_cells[i] is None:
assert xs_cells[i] == batched_xs_cells[i]
else:
assert len(xs_cells[i]) == len(batched_xs_cells[i])
assert torch.equal(xs_cells[i], batched_xs_cells[i])
@pytest.mark.data
def test_data_loader_shuffling():
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
data_loader = DataLoader(dataset, batch_size=32)
unshuffled_ys = []
for data in data_loader:
unshuffled_ys.append(data.y)
data_loader = DataLoader(dataset, batch_size=32, shuffle=True)
shuffled_ys = []
for data in data_loader:
shuffled_ys.append(data.y)
unshuffled_ys = torch.cat(unshuffled_ys, dim=0)
shuffled_ys = torch.cat(shuffled_ys, dim=0)
assert list(unshuffled_ys.size()) == list(shuffled_ys.size())
assert not torch.equal(unshuffled_ys, shuffled_ys)
@pytest.mark.data
def test_idx_splitting_works():
dataset = load_dataset('PROTEINS', max_dim=3, fold=0, init_method='mean')
splits = dataset.get_idx_split()
val_dataset = dataset[splits["valid"]]
ys1 = []
for data in val_dataset:
ys1.append(data.y)
ys2 = []
for i in splits['valid']:
data = dataset.get(i)
ys2.append(data.y)
ys1 = torch.cat(ys1, dim=0)
ys2 = torch.cat(ys2, dim=0)
assert torch.equal(ys1, ys2)
| 46,797 | 43.065913 | 201 | py |
cwn | cwn-main/data/sr_utils.py | import networkx as nx
import torch
from torch_geometric.utils import to_undirected
def load_sr_dataset(path):
"""Load the Strongly Regular Graph Dataset from the supplied path."""
nx_graphs = nx.read_graph6(path)
graphs = list()
for nx_graph in nx_graphs:
n = nx_graph.number_of_nodes()
edge_index = to_undirected(torch.tensor(list(nx_graph.edges()), dtype=torch.long).transpose(1,0))
graphs.append((edge_index, n))
return graphs
| 485 | 29.375 | 105 | py |
cwn | cwn-main/data/__init__.py | 0 | 0 | 0 | py |
|
cwn | cwn-main/data/dummy_complexes.py | import torch
from data.complex import Cochain, Complex
from torch_geometric.data import Data
# TODO: make the features for these dummy complexes disjoint to stress tests even more
def convert_to_graph(complex):
"""Extracts the underlying graph of a cochain complex."""
assert 0 in complex.cochains
assert complex.cochains[0].num_cells > 0
cochain = complex.cochains[0]
x = cochain.x
y = complex.y
edge_attr = None
if cochain.upper_index is None:
edge_index = torch.LongTensor([[], []])
else:
edge_index = cochain.upper_index
if 1 in complex.cochains and complex.cochains[1].x is not None and cochain.shared_coboundaries is not None:
edge_attr = torch.index_select(complex.cochains[1].x, 0, cochain.shared_coboundaries)
if edge_attr is None:
edge_attr = torch.FloatTensor([[]])
graph = Data(x=x, edge_index=edge_index, y=y, edge_attr=edge_attr)
return graph
def get_testing_complex_list():
"""Returns a list of cell complexes used for testing. The list contains many edge cases."""
return [get_fullstop_complex(), get_pyramid_complex(), get_house_complex(), get_kite_complex(), get_square_complex(),
get_square_dot_complex(), get_square_complex(), get_fullstop_complex(), get_house_complex(),
get_kite_complex(), get_pyramid_complex(), get_bridged_complex(), get_square_dot_complex(), get_colon_complex(),
get_filled_square_complex(), get_molecular_complex(), get_fullstop_complex(), get_colon_complex(),
get_bridged_complex(), get_colon_complex(), get_fullstop_complex(), get_fullstop_complex(), get_colon_complex()]
def get_mol_testing_complex_list():
"""Returns a list of cell complexes used for testing. The list contains many edge cases."""
return [get_house_complex(), get_kite_complex(), get_square_complex(), get_fullstop_complex(), get_bridged_complex(),
get_square_dot_complex(), get_square_complex(), get_filled_square_complex(), get_colon_complex(), get_bridged_complex(),
get_kite_complex(), get_square_dot_complex(), get_colon_complex(), get_molecular_complex(), get_bridged_complex(),
get_filled_square_complex(), get_molecular_complex(), get_fullstop_complex(), get_colon_complex()]
def get_house_complex():
"""
Returns the `house graph` below with dummy features.
The `house graph` (3-2-4 is a filled triangle):
4
/ \
3---2
| |
0---1
.
4 5
. 2 .
3 1
. 0 .
.
/0\
.---.
| |
.---.
"""
v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2, 5, 5, 4, 4], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4], [5]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [2, 3], [0, 3], [3, 4], [2, 4]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]).view(-1)], 0)
e_up_index = torch.tensor([[2, 4, 2, 5, 4, 5],
[4, 2, 5, 2, 5, 4]], dtype=torch.long)
e_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long)
e_down_index = torch.tensor([[0, 1, 0, 3, 1, 2, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 4, 5],
[1, 0, 3, 0, 2, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 4]],
dtype=torch.long)
e_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 4, 4],
dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4], [5], [6]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, upper_index=e_up_index, lower_index=e_down_index,
shared_coboundaries=e_shared_coboundaries, shared_boundaries=e_shared_boundaries,
boundary_index=e_boundary_index, y=ye)
t_boundaries = [[2, 4, 5]]
t_boundary_index = torch.stack([
torch.LongTensor(t_boundaries).view(-1),
torch.LongTensor([0, 0, 0]).view(-1)], 0)
t_x = torch.tensor([[1]], dtype=torch.float)
yt = torch.tensor([2], dtype=torch.long)
t_cochain = Cochain(dim=2, x=t_x, y=yt, boundary_index=t_boundary_index)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, t_cochain, y=y)
def get_bridged_complex():
"""
Returns the `bridged graph` below with dummy features.
The `bridged graph` (0-1-4-3, 1-2-3-4, 0-1-2-3 are filled rings):
3---2
|\ |
| 4 |
| \|
0---1
.-2-.
|4 |
3 . 1
| 5|
.-0-.
.---.
|\1 |
| . |
| 0\|
.---.
.---.
| |
| 2 |
| |
.---.
"""
v_up_index = torch.tensor( [[0, 1, 0, 3, 1, 2, 1, 4, 2, 3, 3, 4],
[1, 0, 3, 0, 2, 1, 4, 1, 3, 2, 4, 3]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 5, 5, 2, 2, 4, 4], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4], [5]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [2, 3], [0, 3], [3, 4], [1, 4]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]).view(-1)], 0)
e_up_index = torch.tensor( [[0, 1, 0, 2, 0, 3, 0, 3, 0, 4, 0, 5, 1, 2, 1, 2, 1, 3, 1, 4, 1, 5, 2, 3, 2, 4, 2, 5, 3, 4, 3, 5, 4, 5, 4, 5],
[1, 0, 2, 0, 3, 0, 3, 0, 4, 0, 5, 0, 2, 1, 2, 1, 3, 1, 4, 1, 5, 1, 3, 2, 4, 2, 5, 2, 4, 3, 5, 3, 5, 4, 5, 4]], dtype=torch.long)
e_shared_coboundaries = torch.tensor([2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1], dtype=torch.long)
e_down_index = torch.tensor( [[0, 1, 0, 3, 0, 5, 1, 2, 1, 5, 2, 3, 2, 4, 3, 4, 4, 5],
[1, 0, 3, 0, 5, 0, 2, 1, 5, 1, 3, 2, 4, 2, 4, 3, 5, 4]], dtype=torch.long)
e_shared_boundaries = torch.tensor([1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3, 3, 4, 4], dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4], [5], [6]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, upper_index=e_up_index, lower_index=e_down_index,
shared_coboundaries=e_shared_coboundaries, shared_boundaries=e_shared_boundaries,
boundary_index=e_boundary_index, y=ye)
t_boundaries = [[0, 3, 4, 5], [1, 2, 4, 5], [0, 1, 2, 3]]
t_boundary_index = torch.stack([
torch.LongTensor(t_boundaries).view(-1),
torch.LongTensor([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]).view(-1)], 0)
t_down_index = torch.tensor( [[0, 1, 0, 1, 0, 2, 0, 2, 1, 2, 1, 2],
[1, 0, 1, 0, 2, 0, 2, 0, 2, 1, 2, 1]], dtype=torch.long)
t_shared_boundaries = torch.tensor([4, 4, 5, 5, 0, 0, 3, 3, 1, 1, 2, 2], dtype=torch.long)
t_x = torch.tensor([[1], [2], [3]], dtype=torch.float)
yt = torch.tensor([2, 2, 2], dtype=torch.long)
t_cochain = Cochain(dim=2, x=t_x, y=yt, boundary_index=t_boundary_index, lower_index=t_down_index, shared_boundaries=t_shared_boundaries)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, t_cochain, y=y)
def get_fullstop_complex():
"""
Returns the `fullstop graph` below with dummy features.
The `fullstop graph` is a single isolated node:
0
"""
v_x = torch.tensor([[1]], dtype=torch.float)
yv = torch.tensor([0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, y=yv)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, y=y)
def get_colon_complex():
"""
Returns the `colon graph` below with dummy features.
The `colon graph` is made up of two isolated nodes:
1
0
"""
v_x = torch.tensor([[1], [2]], dtype=torch.float)
yv = torch.tensor([0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, y=yv)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, y=y)
def get_square_complex():
"""
Returns the `square graph` below with dummy features.
The `square graph`:
3---2
| |
0---1
. 2 .
3 1
. 0 .
.---.
| |
.---.
"""
v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3],
[1, 0, 3, 0, 2, 1, 3, 2]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [2, 3], [0, 3]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3]).view(-1)], 0)
e_down_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3],
[1, 0, 3, 0, 2, 1, 3, 2]], dtype=torch.long)
e_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 3, 3], dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1], dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, lower_index=e_down_index, shared_boundaries=e_shared_boundaries, y=ye,
boundary_index=e_boundary_index)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, y=y)
def get_square_dot_complex():
"""
Returns the `square-dot graph` below with dummy features.
The `square-dot graph`:
3---2
| |
0---1 4
. 2 .
3 1
. 0 . .
.---.
| |
.---. .
"""
v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3],
[1, 0, 3, 0, 2, 1, 3, 2]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4], [5]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [2, 3], [0, 3]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3]).view(-1)], 0)
e_down_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3],
[1, 0, 3, 0, 2, 1, 3, 2]], dtype=torch.long)
e_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 3, 3], dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1], dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, lower_index=e_down_index, shared_boundaries=e_shared_boundaries, y=ye,
boundary_index=e_boundary_index)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, y=y)
def get_kite_complex():
"""
Returns the `kite graph` below with dummy features.
The `kite graph`:
2---3---4
/ \ /
0---1
. 4 . 5 .
2 1 3
. 0 .
.---.---.
/0\1/
.---.
"""
v_up_index = torch.tensor([[0, 1, 0, 2, 1, 2, 1, 3, 2, 3, 3, 4],
[1, 0, 2, 0, 2, 1, 3, 1, 3, 2, 4, 3]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 2, 2, 1, 1, 3, 3, 4, 4, 5, 5], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4], [5]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [0, 2], [1, 3], [2, 3], [3, 4]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]).view(-1)], 0)
e_down_index = torch.tensor([[0, 1, 0, 3, 1, 3, 0, 2, 1, 2, 2, 4, 1, 4, 3, 4, 3, 5, 4, 5],
[1, 0, 3, 0, 3, 1, 2, 0, 2, 1, 4, 2, 4, 1, 4, 3, 5, 3, 5, 4]],
dtype=torch.long)
e_shared_boundaries = torch.tensor([1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
dtype=torch.long)
e_up_index = torch.tensor([[0, 1, 0, 2, 1, 2, 1, 3, 1, 4, 3, 4],
[1, 0, 2, 0, 2, 1, 3, 1, 4, 1, 4, 3]], dtype=torch.long)
e_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4], [5], [6]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, lower_index=e_down_index, shared_boundaries=e_shared_boundaries,
upper_index=e_up_index, shared_coboundaries=e_shared_coboundaries, y=ye,
boundary_index=e_boundary_index)
t_boundaries = [[0, 1, 2], [1, 3, 4]]
t_boundary_index = torch.stack([
torch.LongTensor(t_boundaries).view(-1),
torch.LongTensor([0, 0, 0, 1, 1, 1]).view(-1)], 0)
t_down_index = torch.tensor([[0, 1],
[1, 0]], dtype=torch.long)
t_shared_boundaries = torch.tensor([1, 1], dtype=torch.long)
t_x = torch.tensor([[1], [2]], dtype=torch.float)
yt = torch.tensor([2, 2], dtype=torch.long)
t_cochain = Cochain(dim=2, x=t_x, lower_index=t_down_index, shared_boundaries=t_shared_boundaries, y=yt,
boundary_index=t_boundary_index)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, t_cochain, y=y)
def get_pyramid_complex():
"""
Returns the `pyramid` below with dummy features.
The `pyramid` (corresponds to a 4-clique):
3
/|\
/_2_\
0-----1
.
5 4 3
2.1
. 0 .
3
/ \
/ \
2-----1
/ \ / \
/ \ / \
3-----0-----3
.
/ \
4 3
.--1--.
/ 2 0 \
4 \ / 3
.--5--.--5--.
3
/ \
/ 2 \
2-----1
/ \ 0 / \
/ 3 \ / 1 \
3-----0-----3
.
/|\
/_0_\
.-----.
"""
v_up_index = torch.tensor([[0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],
[1, 0, 2, 0, 3, 0, 2, 1, 3, 1, 3, 2]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 2, 2, 5, 5, 1, 1, 3, 3, 4, 4], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
yv = torch.tensor([3, 3, 3, 3], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [0, 2], [1, 3], [2, 3], [0, 3]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]).view(-1)], 0)
e_up_index = torch.tensor(
[[0, 1, 0, 2, 1, 2, 0, 5, 0, 3, 3, 5, 1, 3, 1, 4, 3, 4, 2, 4, 2, 5, 4, 5],
[1, 0, 2, 0, 2, 1, 5, 0, 3, 0, 5, 3, 3, 1, 4, 1, 4, 3, 4, 2, 5, 2, 5, 4]],
dtype=torch.long)
e_shared_coboundaries = torch.tensor(
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3], dtype=torch.long)
e_down_index = torch.tensor(
[[0, 1, 0, 2, 0, 3, 0, 5, 1, 2, 1, 3, 1, 4, 2, 4, 2, 5, 3, 4, 3, 5, 4, 5],
[1, 0, 2, 0, 3, 0, 5, 0, 2, 1, 3, 1, 4, 1, 4, 2, 5, 2, 4, 3, 5, 3, 5, 4]],
dtype=torch.long)
e_shared_boundaries = torch.tensor(
[1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 1, 1, 2, 2, 2, 2, 0, 0, 3, 3, 3, 3, 3, 3], dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4], [5], [6]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, lower_index=e_down_index, upper_index=e_up_index,
shared_boundaries=e_shared_boundaries, shared_coboundaries=e_shared_coboundaries, y=ye,
boundary_index=e_boundary_index)
t_boundaries = [[0, 1, 2], [0, 3, 5], [1, 3, 4], [2, 4, 5]]
t_boundary_index = torch.stack([
torch.LongTensor(t_boundaries).view(-1),
torch.LongTensor([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]).view(-1)], 0)
t_up_index = torch.tensor([[0, 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3],
[1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2]], dtype=torch.long)
t_shared_coboundaries = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
t_down_index = torch.tensor([[0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],
[1, 0, 2, 0, 3, 0, 2, 1, 3, 1, 3, 2]], dtype=torch.long)
t_shared_boundaries = torch.tensor([0, 0, 1, 1, 2, 2, 3, 3, 5, 5, 4, 4], dtype=torch.long)
t_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
yt = torch.tensor([2, 2, 2, 2], dtype=torch.long)
t_cochain = Cochain(dim=2, x=t_x, lower_index=t_down_index, upper_index=t_up_index,
shared_boundaries=t_shared_boundaries, shared_coboundaries=t_shared_coboundaries, y=yt,
boundary_index=t_boundary_index)
p_boundaries = [[0, 1, 2, 3]]
p_boundary_index = torch.stack([
torch.LongTensor(p_boundaries).view(-1),
torch.LongTensor([0, 0, 0, 0]).view(-1)], 0)
p_x = torch.tensor([[1]], dtype=torch.float)
yp = torch.tensor([3], dtype=torch.long)
p_cochain = Cochain(dim=3, x=p_x, y=yp, boundary_index=p_boundary_index)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, t_cochain, p_cochain, y=y)
def get_filled_square_complex():
"""This is a cell / cubical complex formed of a single filled square.
3---2
| |
0---1
. 2 .
3 1
. 0 .
.---.
| 0 |
.---.
"""
v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3],
[1, 0, 3, 0, 2, 1, 3, 2]], dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 2, 2], dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [2, 3], [0, 3]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3]).view(-1)], 0)
e_down_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3],
[1, 0, 3, 0, 2, 1, 3, 2]], dtype=torch.long)
e_shared_boundaries = torch.tensor([1, 1, 0, 0, 2, 2, 3, 3], dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1], dtype=torch.long)
e_upper_index = torch.tensor([[0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],
[1, 0, 2, 0, 3, 0, 2, 1, 3, 1, 3, 2]], dtype=torch.long)
e_shared_coboundaries = torch.tensor([0]*12, dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, lower_index=e_down_index, shared_boundaries=e_shared_boundaries,
upper_index=e_upper_index, y=ye, shared_coboundaries=e_shared_coboundaries, boundary_index=e_boundary_index)
c_boundary_index = torch.LongTensor(
[[0, 1, 2, 3],
[0, 0, 0, 0]]
)
c_x = torch.tensor([[1]], dtype=torch.float)
yc = torch.tensor([2], dtype=torch.long)
c_cochain = Cochain(dim=2, x=c_x, y=yc, boundary_index=c_boundary_index)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, c_cochain, y=y)
def get_molecular_complex():
"""This is a molecule with filled rings.
3---2---4---5
| | |
0---1-------6---7
. 2 . 4 . 5 .
3 1 6
. 0 . 7 . 8 .
.---. --- . --- .
| 0 | 1 |
.---. --------- . ---- .
"""
v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 1, 6, 2, 3, 2, 4, 4, 5, 5, 6, 6, 7],
[1, 0, 3, 0, 2, 1, 6, 1, 3, 2, 4, 2, 5, 4, 6, 5, 7, 6]],
dtype=torch.long)
v_shared_coboundaries = torch.tensor([0, 0, 3, 3, 1, 1, 7, 7, 2, 2, 4, 4, 5, 5, 6, 6, 8, 8],
dtype=torch.long)
v_x = torch.tensor([[1], [2], [3], [4], [5], [6], [7], [8]], dtype=torch.float)
yv = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0], dtype=torch.long)
v_cochain = Cochain(dim=0, x=v_x, upper_index=v_up_index, shared_coboundaries=v_shared_coboundaries, y=yv)
e_boundaries = [[0, 1], [1, 2], [2, 3], [0, 3], [1, 6], [2, 4], [4, 5], [5, 6], [6, 7]]
e_boundary_index = torch.stack([
torch.LongTensor(e_boundaries).view(-1),
torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 7, 7, 4, 4, 5, 5, 6, 6, 8, 8]).view(-1)], 0)
e_down_index = torch.tensor(
[[0, 1, 0, 3, 1, 2, 2, 3, 1, 4, 2, 4, 4, 5, 5, 6, 6, 7, 6, 8, 7, 8, 0, 7, 1, 7],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 1, 4, 2, 5, 4, 6, 5, 7, 6, 8, 6, 8, 7, 7, 0, 7, 1]],
dtype=torch.long)
e_shared_boundaries = torch.tensor(
[1, 1, 0, 0, 2, 2, 3, 3, 2, 2, 2, 2, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1],
dtype=torch.long)
e_x = torch.tensor([[1], [2], [3], [4], [5], [6], [7], [8], [9]], dtype=torch.float)
ye = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=torch.long)
e_upper_index_c1 = torch.tensor([[0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],
[1, 0, 2, 0, 3, 0, 2, 1, 3, 1, 3, 2]], dtype=torch.long)
e_upper_index_c2 = torch.tensor([[1, 4, 1, 5, 1, 6, 1, 7, 4, 5, 4, 6, 4, 7, 5, 6, 5, 7, 6, 7],
[4, 1, 5, 1, 6, 1, 7, 1, 5, 4, 6, 4, 7, 4, 6, 5, 7, 5, 7, 6]],
dtype=torch.long)
e_upper_index = torch.cat((e_upper_index_c1, e_upper_index_c2), dim=-1)
e_shared_coboundaries = torch.tensor([0]*12 + [1]*20, dtype=torch.long)
e_cochain = Cochain(dim=1, x=e_x, lower_index=e_down_index, shared_boundaries=e_shared_boundaries,
upper_index=e_upper_index, y=ye, shared_coboundaries=e_shared_coboundaries, boundary_index=e_boundary_index)
c_boundary_index = torch.LongTensor(
[[0, 1, 2, 3, 1, 4, 5, 6, 7],
[0, 0, 0, 0, 1, 1, 1, 1, 1]]
)
c_x = torch.tensor([[1], [2]], dtype=torch.float)
c_down_index = torch.tensor([[0, 1],
[1, 0]], dtype=torch.long)
c_shared_boundaries = torch.tensor([1, 1], dtype=torch.long)
yc = torch.tensor([2, 2], dtype=torch.long)
c_cochain = Cochain(dim=2, x=c_x, y=yc, boundary_index=c_boundary_index, lower_index=c_down_index,
shared_boundaries=c_shared_boundaries)
y = torch.LongTensor([v_x.shape[0]])
return Complex(v_cochain, e_cochain, c_cochain, y=y)
| 23,206 | 39.220104 | 168 | py |
cwn | cwn-main/data/parallel.py | from tqdm.auto import tqdm
from joblib import Parallel
class ProgressParallel(Parallel):
"""A helper class for adding tqdm progressbar to the joblib library."""
def __init__(self, use_tqdm=True, total=None, *args, **kwargs):
self._use_tqdm = use_tqdm
self._total = total
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
with tqdm(disable=not self._use_tqdm, total=self._total) as self._pbar:
return Parallel.__call__(self, *args, **kwargs)
def print_progress(self):
if self._total is None:
self._pbar.total = self.n_dispatched_tasks
self._pbar.n = self.n_completed_tasks
self._pbar.refresh()
| 714 | 33.047619 | 79 | py |
cwn | cwn-main/data/test_utils.py | import torch
from torch_geometric.data import Data
from data.utils import compute_clique_complex_with_gudhi, compute_ring_2complex
from data.utils import convert_graph_dataset_with_gudhi, convert_graph_dataset_with_rings
from data.complex import ComplexBatch
from data.dummy_complexes import convert_to_graph, get_testing_complex_list
import pytest
# TODO: Gudhi does not preserve the order of the edges in edge_index. It uses a lexicographic order
# Once we care about edge_features at initialisation, we need to make the order the same.
# Define here below the `house graph` and the expected connectivity to be constructed.
# The `house graph` (3-2-4 is a filled triangle):
# 4
# / \
# 3---2
# | |
# 0---1
#
# .
# 4 5
# . 2 .
# 3 1
# . 0 .
#
# .
# /0\
# .---.
# | |
# .---.
@pytest.fixture
def house_edge_index():
return torch.tensor([[0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4],
[1, 3, 0, 2, 1, 3, 4, 0, 2, 4, 2, 3]], dtype=torch.long)
def test_gudhi_clique_complex(house_edge_index):
'''
4
/ \
3---2
| |
0---1
.
5 4
. 3 .
1 2
. 0 .
.
/0\
.---.
| |
.---.
'''
house = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house.num_nodes = house_edge_index.max().item() + 1
house_complex = compute_clique_complex_with_gudhi(house.x, house.edge_index, house.num_nodes,
y=house.y)
# Check the number of simplices
assert house_complex.nodes.num_cells_down is None
assert house_complex.nodes.num_cells_up == 6
assert house_complex.edges.num_cells_down == 5
assert house_complex.edges.num_cells_up == 1
assert house_complex.two_cells.num_cells_down == 6
assert house_complex.two_cells.num_cells_up == 0
# Check the returned parameters
v_params = house_complex.get_cochain_params(dim=0)
assert torch.equal(v_params.x, house.x)
assert v_params.down_index is None
expected_v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3]], dtype=torch.long)
assert torch.equal(v_params.up_index, expected_v_up_index)
expected_v_up_attr = torch.tensor([[1], [1], [3], [3], [3], [3],
[5], [5], [6], [6], [7], [7]], dtype=torch.float)
assert torch.equal(v_params.kwargs['up_attr'], expected_v_up_attr)
assert v_params.kwargs['down_attr'] is None
assert v_params.kwargs['boundary_attr'] is None
e_params = house_complex.get_cochain_params(dim=1)
expected_e_x = torch.tensor([[1], [3], [3], [5], [6], [7]], dtype=torch.float)
assert torch.equal(e_params.x, expected_e_x)
expected_e_up_index = torch.tensor([[3, 4, 3, 5, 4, 5],
[4, 3, 5, 3, 5, 4]], dtype=torch.long)
assert torch.equal(e_params.up_index, expected_e_up_index)
expected_e_up_attr = torch.tensor([[9], [9], [9], [9], [9], [9]], dtype=torch.float)
assert torch.equal(e_params.kwargs['up_attr'], expected_e_up_attr)
expected_e_down_index = torch.tensor([[0, 1, 0, 2, 2, 3, 2, 4, 3, 4, 1, 3, 1, 5, 3, 5, 4, 5],
[1, 0, 2, 0, 3, 2, 4, 2, 4, 3, 3, 1, 5, 1, 5, 3, 5, 4]],
dtype=torch.long)
assert torch.equal(e_params.down_index, expected_e_down_index)
expected_e_down_attr = torch.tensor([[0], [0], [1], [1], [2], [2], [2], [2], [2], [2],
[3], [3], [3], [3], [3], [3], [4], [4]],
dtype=torch.float)
assert torch.equal(e_params.kwargs['down_attr'], expected_e_down_attr)
assert torch.equal(e_params.kwargs['boundary_attr'], house.x)
assert list(e_params.kwargs['boundary_index'].size()) == [2, 2*house_complex.edges.num_cells]
assert torch.equal(e_params.kwargs['boundary_index'][1], torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))
assert torch.equal(e_params.kwargs['boundary_index'][0], torch.LongTensor([0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4]))
t_params = house_complex.get_cochain_params(dim=2)
expected_t_x = torch.tensor([[9]], dtype=torch.float)
assert torch.equal(t_params.x, expected_t_x)
assert t_params.down_index is None
assert t_params.up_index is None
assert torch.equal(t_params.kwargs['boundary_attr'], expected_e_x)
assert list(t_params.kwargs['boundary_index'].size()) == [2, 3*house_complex.two_cells.num_cells]
assert torch.equal(t_params.kwargs['boundary_index'][1], torch.LongTensor([0, 0, 0]))
assert torch.equal(t_params.kwargs['boundary_index'][0], torch.LongTensor([3, 4, 5]))
assert torch.equal(house_complex.y, house.y)
def test_gudhi_clique_complex_dataset_conversion(house_edge_index):
house1 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house2 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house3 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
dataset = [house1, house2, house3]
complexes, dim, num_features = convert_graph_dataset_with_gudhi(dataset, expansion_dim=3)
assert dim == 2
assert len(num_features) == 3
for i in range(len(num_features)):
assert num_features[i] == 1
assert len(complexes) == 3
for i in range(len(complexes)):
# Do some basic checks for each complex.
assert complexes[i].dimension == 2
assert complexes[i].nodes.boundary_index is None
assert list(complexes[i].edges.boundary_index.size()) == [2, 2*6]
assert list(complexes[i].two_cells.boundary_index.size()) == [2, 3*1]
assert complexes[i].edges.lower_index.size(1) == 18
assert torch.equal(complexes[i].nodes.x, house1.x)
assert torch.equal(complexes[i].y, house1.y)
def test_gudhi_clique_complex_dataset_conversion_with_down_adj_excluded(house_edge_index):
house1 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house2 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house3 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
dataset = [house1, house2, house3]
complexes, dim, num_features = convert_graph_dataset_with_gudhi(dataset, expansion_dim=3,
include_down_adj=False)
assert dim == 2
assert len(num_features) == 3
for i in range(len(num_features)):
assert num_features[i] == 1
assert len(complexes) == 3
for i in range(len(complexes)):
# Do some basic checks for each complex.
assert complexes[i].dimension == 2
assert complexes[i].nodes.boundary_index is None
assert list(complexes[i].edges.boundary_index.size()) == [2, 2*6]
assert list(complexes[i].two_cells.boundary_index.size()) == [2, 3*1]
assert complexes[i].edges.lower_index is None
assert torch.equal(complexes[i].nodes.x, house1.x)
assert torch.equal(complexes[i].y, house1.y)
def test_gudhi_integration_with_batching_without_adj(house_edge_index):
house1 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1),
y=torch.tensor([1]))
house2 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1),
y=torch.tensor([1]))
house3 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1),
y=torch.tensor([1]))
dataset = [house1, house2, house3]
# Without down-adj
complexes, dim, num_features = convert_graph_dataset_with_gudhi(dataset, expansion_dim=3,
include_down_adj=False)
batch = ComplexBatch.from_complex_list(complexes)
assert batch.dimension == 2
assert batch.edges.lower_index is None
assert batch.nodes.boundary_index is None
assert list(batch.edges.boundary_index.size()) == [2, 3*2*6]
assert list(batch.two_cells.boundary_index.size()) == [2, 1*3*3]
def test_gudhi_integration_with_batching_with_adj(house_edge_index):
house1 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1),
y=torch.tensor([1]))
house2 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1),
y=torch.tensor([1]))
house3 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1),
y=torch.tensor([1]))
dataset = [house1, house2, house3]
# Without down-adj
complexes, dim, num_features = convert_graph_dataset_with_gudhi(dataset, expansion_dim=3,
include_down_adj=True)
batch = ComplexBatch.from_complex_list(complexes)
assert batch.dimension == 2
assert batch.edges.lower_index.size(1) == 18*3
assert list(batch.edges.boundary_index.size()) == [2, 3*2*6]
assert list(batch.two_cells.boundary_index.size()) == [2, 1*3*3]
def test_construction_of_ring_2complex(house_edge_index):
house = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house.num_nodes = house_edge_index.max().item() + 1
house_complex = compute_ring_2complex(house.x, house.edge_index, None, house.num_nodes,
max_k=4, y=house.y, init_rings=True)
# Check the number of cells
assert house_complex.nodes.num_cells_down is None
assert house_complex.nodes.num_cells_up == 6
assert house_complex.nodes.boundary_index is None
assert house_complex.edges.num_cells_down == 5
assert house_complex.edges.num_cells_up == 2
assert list(house_complex.edges.boundary_index.size()) == [2, 2*6]
assert house_complex.cochains[2].num_cells == 2
assert house_complex.cochains[2].num_cells_down == 6
assert house_complex.cochains[2].num_cells_up == 0
assert list(house_complex.cochains[2].boundary_index.size()) == [2, 3+4]
# Check the returned parameters
v_params = house_complex.get_cochain_params(dim=0)
assert torch.equal(v_params.x, house.x)
assert v_params.down_index is None
expected_v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3]], dtype=torch.long)
assert torch.equal(v_params.up_index, expected_v_up_index)
expected_v_up_attr = torch.tensor([[1], [1], [3], [3], [3], [3],
[5], [5], [6], [6], [7], [7]], dtype=torch.float)
assert torch.equal(v_params.kwargs['up_attr'], expected_v_up_attr)
assert v_params.kwargs['down_attr'] is None
assert v_params.kwargs['boundary_attr'] is None
e_params = house_complex.get_cochain_params(dim=1)
expected_e_x = torch.tensor([[1], [3], [3], [5], [6], [7]], dtype=torch.float)
assert torch.equal(e_params.x, expected_e_x)
expected_e_up_index = torch.tensor([[0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3, 3, 4, 3, 5, 4, 5],
[1, 0, 2, 0, 3, 0, 2, 1, 3, 1, 3, 2, 4, 3, 5, 3, 5, 4]], dtype=torch.long)
assert torch.equal(e_params.up_index, expected_e_up_index)
expected_e_up_attr = torch.tensor([[6], [6], [6], [6], [6], [6], [6], [6], [6], [6], [6], [6], [9], [9], [9], [9], [9], [9]], dtype=torch.float)
assert torch.equal(e_params.kwargs['up_attr'], expected_e_up_attr)
expected_e_down_index = torch.tensor([[0, 1, 0, 2, 2, 3, 2, 4, 3, 4, 1, 3, 1, 5, 3, 5, 4, 5],
[1, 0, 2, 0, 3, 2, 4, 2, 4, 3, 3, 1, 5, 1, 5, 3, 5, 4]],
dtype=torch.long)
assert torch.equal(e_params.down_index, expected_e_down_index)
expected_e_down_attr = torch.tensor([[0], [0], [1], [1], [2], [2], [2], [2], [2], [2],
[3], [3], [3], [3], [3], [3], [4], [4]],
dtype=torch.float)
assert torch.equal(e_params.kwargs['down_attr'], expected_e_down_attr)
assert torch.equal(e_params.kwargs['boundary_attr'], house.x)
assert list(e_params.kwargs['boundary_index'].size()) == [2, 2*house_complex.edges.num_cells]
assert torch.equal(e_params.kwargs['boundary_index'][1], torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))
assert torch.equal(e_params.kwargs['boundary_index'][0], torch.LongTensor([0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4]))
t_params = house_complex.get_cochain_params(dim=2)
expected_t_x = torch.tensor([[6], [9]], dtype=torch.float)
assert torch.equal(t_params.x, expected_t_x)
expected_t_down_index = torch.tensor([[0, 1],
[1, 0]],
dtype=torch.long)
assert torch.equal(t_params.down_index, expected_t_down_index)
expected_t_down_attr = torch.tensor([[5], [5]], dtype=torch.float)
assert torch.equal(t_params.kwargs['down_attr'], expected_t_down_attr)
assert t_params.up_index is None
assert torch.equal(t_params.kwargs['boundary_attr'], expected_e_x)
expected_t_boundary_index = torch.tensor([[0, 1, 2, 3, 3, 4, 5],
[0, 0, 0, 0, 1, 1, 1]], dtype=torch.long)
assert torch.equal(t_params.kwargs['boundary_index'], expected_t_boundary_index)
assert torch.equal(house_complex.y, house.y)
def test_construction_of_ring_2complex_with_edge_feats(house_edge_index):
'''
4
/ \
3---2
| |
0---1
.
5 4
. 3 .
1 2
. 0 .
.
/0\
.---.
| 1 |
.---.
'''
edge_attr = torch.FloatTensor(
[[0.0, 1.0],
[0.0, 3.0],
[0.0, 1.0],
[1.0, 2.0],
[1.0, 2.0],
[2.0, 3.0],
[2.0, 4.0],
[0.0, 3.0],
[2.0, 3.0],
[3.0, 4.0],
[2.0, 4.0],
[3.0, 4.0]])
house = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]),
edge_attr=edge_attr)
house.num_nodes = house_edge_index.max().item() + 1
house_complex = compute_ring_2complex(house.x, house.edge_index, house.edge_attr, house.num_nodes,
max_k=4, y=house.y, init_rings=False)
# Check the number of cells
assert house_complex.nodes.num_cells_down is None
assert house_complex.nodes.num_cells_up == 6
assert house_complex.nodes.boundary_index is None
assert house_complex.edges.num_cells_down == 5
assert house_complex.edges.num_cells_up == 2
assert list(house_complex.edges.boundary_index.size()) == [2, 2*6]
assert house_complex.cochains[2].num_cells == 2
assert house_complex.cochains[2].num_cells_down == 6
assert house_complex.cochains[2].num_cells_up == 0
assert list(house_complex.cochains[2].boundary_index.size()) == [2, 3+4]
# Check the returned parameters
v_params = house_complex.get_cochain_params(dim=0)
assert torch.equal(v_params.x, house.x)
assert v_params.down_index is None
expected_v_up_index = torch.tensor([[0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4],
[1, 0, 3, 0, 2, 1, 3, 2, 4, 2, 4, 3]], dtype=torch.long)
assert torch.equal(v_params.up_index, expected_v_up_index)
expected_v_up_attr = torch.tensor([[0.0, 1.0], [0.0, 1.0], [0.0, 3.0], [0.0, 3.0],
[1.0, 2.0], [1.0, 2.0], [2.0, 3.0], [2.0, 3.0],
[2.0, 4.0], [2.0, 4.0], [3.0, 4.0], [3.0, 4.0]], dtype=torch.float)
assert torch.equal(v_params.kwargs['up_attr'], expected_v_up_attr)
assert v_params.kwargs['down_attr'] is None
assert v_params.kwargs['boundary_attr'] is None
e_params = house_complex.get_cochain_params(dim=1)
expected_e_x = torch.FloatTensor(
[[0.0, 1.0],
[0.0, 3.0],
[1.0, 2.0],
[2.0, 3.0],
[2.0, 4.0],
[3.0, 4.0]])
assert torch.equal(e_params.x, expected_e_x)
expected_e_up_index = torch.tensor([[0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3, 3, 4, 3, 5, 4, 5],
[1, 0, 2, 0, 3, 0, 2, 1, 3, 1, 3, 2, 4, 3, 5, 3, 5, 4]], dtype=torch.long)
assert torch.equal(e_params.up_index, expected_e_up_index)
assert e_params.kwargs['up_attr'] is None
expected_e_down_index = torch.tensor([[0, 1, 0, 2, 2, 3, 2, 4, 3, 4, 1, 3, 1, 5, 3, 5, 4, 5],
[1, 0, 2, 0, 3, 2, 4, 2, 4, 3, 3, 1, 5, 1, 5, 3, 5, 4]],
dtype=torch.long)
assert torch.equal(e_params.down_index, expected_e_down_index)
expected_e_down_attr = torch.tensor([[0], [0], [1], [1], [2], [2], [2], [2], [2], [2],
[3], [3], [3], [3], [3], [3], [4], [4]],
dtype=torch.float)
assert torch.equal(e_params.kwargs['down_attr'], expected_e_down_attr)
assert torch.equal(e_params.kwargs['boundary_attr'], house.x)
assert list(e_params.kwargs['boundary_index'].size()) == [2, 2*house_complex.edges.num_cells]
assert torch.equal(e_params.kwargs['boundary_index'][1], torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))
assert torch.equal(e_params.kwargs['boundary_index'][0], torch.LongTensor([0, 1, 0, 3, 1, 2, 2, 3, 2, 4, 3, 4]))
t_params = house_complex.get_cochain_params(dim=2)
assert t_params.x is None
expected_t_down_index = torch.tensor([[0, 1],
[1, 0]],
dtype=torch.long)
assert torch.equal(t_params.down_index, expected_t_down_index)
expected_t_down_attr = torch.tensor([[2.0, 3.0], [2.0, 3.0]], dtype=torch.float)
assert torch.equal(t_params.kwargs['down_attr'], expected_t_down_attr)
assert t_params.up_index is None
assert torch.equal(t_params.kwargs['boundary_attr'], expected_e_x)
expected_t_boundary_index = torch.tensor([[0, 1, 2, 3, 3, 4, 5],
[0, 0, 0, 0, 1, 1, 1]], dtype=torch.long)
assert torch.equal(t_params.kwargs['boundary_index'], expected_t_boundary_index)
assert torch.equal(house_complex.y, house.y)
def test_construction_of_ring_2complex_with_larger_k_size(house_edge_index):
# Here we check that the max ring size does not have any effect when it is larger
# then the largest ring present in the original graph
house = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house.num_nodes = house_edge_index.max().item() + 1
house_cell_a = compute_ring_2complex(house.x, house.edge_index, None, house.num_nodes,
max_k=4, y=house.y, init_rings=True)
house_cell_b = compute_ring_2complex(house.x, house.edge_index, None, house.num_nodes,
max_k=10, y=house.y, init_rings=True)
# Check the number of cells
assert house_cell_a.nodes.num_cells_down is None
assert house_cell_b.nodes.num_cells_down is None
assert house_cell_a.nodes.num_cells_up == house_cell_b.nodes.num_cells_up
assert house_cell_a.nodes.boundary_index is None
assert house_cell_b.nodes.boundary_index is None
assert house_cell_a.edges.num_cells_down == house_cell_b.edges.num_cells_down
assert house_cell_a.edges.num_cells_up == house_cell_b.edges.num_cells_up
assert list(house_cell_a.edges.boundary_index.size()) == list(house_cell_b.edges.boundary_index.size())
assert house_cell_a.two_cells.num_cells == 2 # We have 2 rings in the house complex
assert house_cell_a.two_cells.num_cells == house_cell_b.two_cells.num_cells
assert house_cell_a.two_cells.num_cells_down == house_cell_b.two_cells.num_cells_down
assert house_cell_a.two_cells.num_cells_up == house_cell_b.two_cells.num_cells_up
assert list(house_cell_a.two_cells.boundary_index.size()) == list(house_cell_b.two_cells.boundary_index.size())
# Check the returned node parameters
v_params_a = house_cell_a.get_cochain_params(dim=0)
v_params_b = house_cell_b.get_cochain_params(dim=0)
assert torch.equal(v_params_a.x, v_params_b.x)
assert v_params_a.down_index is None
assert v_params_b.down_index is None
assert torch.equal(v_params_a.up_index, v_params_b.up_index)
assert torch.equal(v_params_a.kwargs['up_attr'], v_params_b.kwargs['up_attr'])
assert v_params_a.kwargs['down_attr'] is None
assert v_params_b.kwargs['down_attr'] is None
assert v_params_a.kwargs['boundary_attr'] is None
assert v_params_b.kwargs['boundary_attr'] is None
# Check the returned edge parameters
e_params_a = house_cell_a.get_cochain_params(dim=1)
e_params_b = house_cell_b.get_cochain_params(dim=1)
assert torch.equal(e_params_a.x, e_params_b.x)
assert torch.equal(e_params_a.up_index, e_params_b.up_index)
assert torch.equal(e_params_a.kwargs['up_attr'], e_params_b.kwargs['up_attr'])
assert torch.equal(e_params_a.down_index, e_params_b.down_index)
assert torch.equal(e_params_a.kwargs['down_attr'], e_params_b.kwargs['down_attr'])
assert torch.equal(e_params_a.kwargs['boundary_attr'], e_params_b.kwargs['boundary_attr'])
assert list(e_params_a.kwargs['boundary_index'].size()) == list(e_params_b.kwargs['boundary_index'].size())
assert torch.equal(e_params_a.kwargs['boundary_index'][1], e_params_b.kwargs['boundary_index'][1])
assert torch.equal(e_params_a.kwargs['boundary_index'][0], e_params_b.kwargs['boundary_index'][0])
# Check the returned ring parameters
t_params_a = house_cell_a.get_cochain_params(dim=2)
t_params_b = house_cell_b.get_cochain_params(dim=2)
assert t_params_a.x.size(0) == 2
assert torch.equal(t_params_a.x, t_params_b.x)
assert torch.equal(t_params_a.down_index, t_params_b.down_index)
assert torch.equal(t_params_a.kwargs['down_attr'], t_params_b.kwargs['down_attr'])
assert t_params_a.up_index is None
assert t_params_b.up_index is None
assert t_params_a.kwargs['up_attr'] is None
assert t_params_b.kwargs['up_attr'] is None
assert torch.equal(t_params_a.kwargs['boundary_attr'], t_params_b.kwargs['boundary_attr'])
assert torch.equal(t_params_a.kwargs['boundary_index'], t_params_b.kwargs['boundary_index'])
# Check label
assert torch.equal(house_cell_a.y, house_cell_b.y)
def test_construction_of_ring_2complex_with_smaller_k_size(house_edge_index):
# Here we check that when we consider rings up to length 3, then the output cell complex
# exactly corresponds to a 2-simplicial complex extracted with the alternative routine
house = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house.num_nodes = house_edge_index.max().item() + 1
house_cell = compute_ring_2complex(house.x, house.edge_index, None, house.num_nodes,
max_k=3, y=house.y, init_rings=True)
house_simp = compute_clique_complex_with_gudhi(house.x, house.edge_index, house.num_nodes,
y=house.y)
# Check the number of cells
assert house_cell.nodes.num_cells_down is None
assert house_simp.nodes.num_cells_down is None
assert house_cell.nodes.num_cells_up == house_simp.nodes.num_cells_up
assert house_cell.nodes.boundary_index is None
assert house_simp.nodes.boundary_index is None
assert house_cell.edges.num_cells_down == house_simp.edges.num_cells_down
assert house_cell.edges.num_cells_up == house_simp.edges.num_cells_up
assert list(house_cell.edges.boundary_index.size()) == list(house_simp.edges.boundary_index.size())
assert house_cell.two_cells.num_cells == 1
assert house_cell.two_cells.num_cells == house_simp.two_cells.num_cells
assert house_cell.two_cells.num_cells_down == house_simp.two_cells.num_cells_down
assert house_cell.two_cells.num_cells_up == house_simp.two_cells.num_cells_up
assert list(house_cell.two_cells.boundary_index.size()) == list(house_simp.two_cells.boundary_index.size())
# Check the returned node parameters
v_params_a = house_cell.get_cochain_params(dim=0)
v_params_b = house_simp.get_cochain_params(dim=0)
assert torch.equal(v_params_a.x, v_params_b.x)
assert v_params_a.down_index is None
assert v_params_b.down_index is None
assert torch.equal(v_params_a.up_index, v_params_b.up_index)
assert torch.equal(v_params_a.kwargs['up_attr'], v_params_b.kwargs['up_attr'])
assert v_params_a.kwargs['down_attr'] is None
assert v_params_b.kwargs['down_attr'] is None
assert v_params_a.kwargs['boundary_attr'] is None
assert v_params_b.kwargs['boundary_attr'] is None
# Check the returned edge parameters
e_params_a = house_cell.get_cochain_params(dim=1)
e_params_b = house_simp.get_cochain_params(dim=1)
assert torch.equal(e_params_a.x, e_params_b.x)
assert torch.equal(e_params_a.up_index, e_params_b.up_index)
assert torch.equal(e_params_a.kwargs['up_attr'], e_params_b.kwargs['up_attr'])
assert torch.equal(e_params_a.down_index, e_params_b.down_index)
assert torch.equal(e_params_a.kwargs['down_attr'], e_params_b.kwargs['down_attr'])
assert torch.equal(e_params_a.kwargs['boundary_attr'], e_params_b.kwargs['boundary_attr'])
assert list(e_params_a.kwargs['boundary_index'].size()) == list(e_params_b.kwargs['boundary_index'].size())
assert torch.equal(e_params_a.kwargs['boundary_index'][1], e_params_b.kwargs['boundary_index'][1])
assert torch.equal(e_params_a.kwargs['boundary_index'][0], e_params_b.kwargs['boundary_index'][0])
# Check the returned ring parameters
t_params_a = house_cell.get_cochain_params(dim=2)
t_params_b = house_simp.get_cochain_params(dim=2)
assert t_params_a.x.size(0) == 1
assert torch.equal(t_params_a.x, t_params_b.x)
assert t_params_a.down_index is None
assert t_params_b.down_index is None
assert t_params_a.kwargs['down_attr'] is None
assert t_params_b.kwargs['down_attr'] is None
assert t_params_a.up_index is None
assert t_params_b.up_index is None
assert t_params_a.kwargs['up_attr'] is None
assert t_params_b.kwargs['up_attr'] is None
assert torch.equal(t_params_a.kwargs['boundary_attr'], t_params_b.kwargs['boundary_attr'])
assert torch.equal(t_params_a.kwargs['boundary_index'], t_params_b.kwargs['boundary_index'])
# Check label
assert torch.equal(house_cell.y, house_simp.y)
def test_ring_2complex_dataset_conversion(house_edge_index):
house1 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house2 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
house3 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), y=torch.tensor([1]))
dataset = [house1, house2, house3]
complexes, dim, num_features = convert_graph_dataset_with_rings(dataset, include_down_adj=True,
init_rings=True)
assert dim == 2
assert len(num_features) == 3
for i in range(len(num_features)):
assert num_features[i] == 1
assert len(complexes) == 3
for i in range(len(complexes)):
# Do some basic checks for each complex.
# Checks the number of rings in `boundary_index`
assert complexes[i].cochains[2].boundary_index[:, 1].max().item() == 1
assert complexes[i].dimension == 2
assert complexes[i].nodes.boundary_index is None
assert list(complexes[i].edges.boundary_index.size()) == [2, 2*6]
assert list(complexes[i].two_cells.boundary_index.size()) == [2, 3+4]
assert complexes[i].edges.lower_index.size(1) == 18
assert torch.equal(complexes[i].nodes.x, house1.x)
assert torch.equal(complexes[i].y, house1.y)
def test_ring_2complex_dataset_conversion_with_edge_feats(house_edge_index):
edge_attr = torch.FloatTensor(
[[0.0, 1.0],
[0.0, 3.0],
[0.0, 1.0],
[1.0, 2.0],
[1.0, 2.0],
[2.0, 3.0],
[2.0, 4.0],
[0.0, 3.0],
[2.0, 3.0],
[3.0, 4.0],
[2.0, 4.0],
[3.0, 4.0]])
e_x = torch.FloatTensor(
[[0.0, 1.0],
[0.0, 3.0],
[1.0, 2.0],
[2.0, 3.0],
[2.0, 4.0],
[3.0, 4.0]])
house1 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), edge_attr=edge_attr, y=torch.tensor([1]))
house2 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), edge_attr=edge_attr, y=torch.tensor([1]))
house3 = Data(edge_index=house_edge_index, x=torch.arange(0, 5, dtype=torch.float).view(5, 1), edge_attr=edge_attr, y=torch.tensor([1]))
dataset = [house1, house2, house3]
complexes, dim, num_features = convert_graph_dataset_with_rings(dataset,
init_edges=True, include_down_adj=True, init_rings=False)
assert dim == 2
assert len(num_features) == 3
assert num_features[0] == 1
assert num_features[1] == 2
assert num_features[2] == 0
assert len(complexes) == 3
for i in range(len(complexes)):
# Do some basic checks for each complex.
assert complexes[i].dimension == 2
assert complexes[i].nodes.boundary_index is None
assert list(complexes[i].edges.boundary_index.size()) == [2, 2*6]
assert list(complexes[i].two_cells.boundary_index.size()) == [2, 3+4]
assert complexes[i].edges.lower_index.size(1) == 18
assert torch.equal(complexes[i].nodes.x, house1.x)
assert torch.equal(complexes[i].edges.x, e_x)
assert complexes[i].two_cells.x is None
assert torch.equal(complexes[i].y, house1.y)
def test_simp_complex_conversion_completes():
graphs = list(map(convert_to_graph, get_testing_complex_list()))
_ = convert_graph_dataset_with_gudhi(graphs, expansion_dim=3)
def test_cell_complex_conversion_completes():
graphs = list(map(convert_to_graph, get_testing_complex_list()))
_ = convert_graph_dataset_with_rings(graphs, init_rings=True)
| 31,625 | 48.883281 | 148 | py |
cwn | cwn-main/data/datasets/test_flow.py | import numpy as np
import torch
from scipy.spatial import Delaunay
from data.datasets.flow_utils import load_flow_dataset, create_hole, is_inside_rectangle
def test_create_hole():
# This seed contains some edge cases.
np.random.seed(4)
points = np.random.uniform(size=(400, 2))
tri = Delaunay(points)
hole1 = np.array([[0.2, 0.2], [0.4, 0.4]])
points, triangles = create_hole(points, tri.simplices, hole1)
assert triangles.max() == len(points) - 1
assert triangles.min() == 0
# Check all points are outside the hole
for i in range(len(points)):
assert not is_inside_rectangle(points[i], hole1)
# Double check each point appears in some triangle.
for i in range(len(points)):
assert np.sum(triangles == i) > 0
def test_flow_util_dataset_loading():
# Fix seed for reproducibility
np.random.seed(0)
train, test, _ = load_flow_dataset(num_points=300, num_train=20, num_test=10)
assert len(train) == 20
assert len(test) == 10
label_count = {0: 0, 1: 0}
for cochain in train + test:
# checks x values (flow direction) are either +1 or -1
assert (torch.sum(cochain.x == 1) + torch.sum(cochain.x == -1)
== torch.count_nonzero(cochain.x))
# checks the upper/lower orientation features are consistent
# in shape with the upper/lower indices
assert len(cochain.upper_orient) == cochain.upper_index.size(1)
assert len(cochain.lower_orient) == cochain.lower_index.size(1)
# checks the upper and lower indices are consistent with the number of edges
assert cochain.upper_index.max() < cochain.x.size(0), print(cochain.upper_index.max(),
cochain.x.size(0))
assert cochain.lower_index.max() < cochain.x.size(0), print(cochain.lower_index.max(),
cochain.x.size(0))
# checks the values for orientations are either +1 (coherent) or -1 (not coherent)
assert (torch.sum(cochain.upper_orient == 1)
+ torch.sum(cochain.upper_orient == -1) == cochain.upper_orient.numel())
assert (torch.sum(cochain.lower_orient == 1)
+ torch.sum(cochain.lower_orient == -1) == cochain.lower_orient.numel())
label_count[cochain.y.item()] += 1
# checks distribution of labels
assert label_count[0] == 20 // 2 + 10 // 2
assert label_count[1] == 20 // 2 + 10 // 2
| 2,416 | 36.184615 | 94 | py |
cwn | cwn-main/data/datasets/peptides_structural.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 2 21:37:42 2023
@author: renz
"""
import hashlib
import os.path as osp
import os
import pickle
import shutil
import pandas as pd
import torch
from ogb.utils import smiles2graph
from ogb.utils.torch_util import replace_numpy_with_torchtensor
from ogb.utils.url import decide_download
from torch_geometric.data import Data, download_url
from torch_geometric.data import InMemoryDataset
from data.utils import convert_graph_dataset_with_rings
from data.datasets import InMemoryComplexDataset
from tqdm import tqdm
class PeptidesStructuralDataset(InMemoryComplexDataset):
"""
PyG dataset of 15,535 small peptides represented as their molecular
graph (SMILES) with 11 regression targets derived from the peptide's
3D structure.
The original amino acid sequence representation is provided in
'peptide_seq' and the distance between atoms in 'self_dist_matrix' field
of the dataset file, but not used here as any part of the input.
The 11 regression targets were precomputed from molecule XYZ:
Inertia_mass_[a-c]: The principal component of the inertia of the
mass, with some normalizations. Sorted
Inertia_valence_[a-c]: The principal component of the inertia of the
Hydrogen atoms. This is basically a measure of the 3D
distribution of hydrogens. Sorted
length_[a-c]: The length around the 3 main geometric axis of
the 3D objects (without considering atom types). Sorted
Spherocity: SpherocityIndex descriptor computed by
rdkit.Chem.rdMolDescriptors.CalcSpherocityIndex
Plane_best_fit: Plane of best fit (PBF) descriptor computed by
rdkit.Chem.rdMolDescriptors.CalcPBF
Args:
root (string): Root directory where the dataset should be saved.
smiles2graph (callable): A callable function that converts a SMILES
string into a graph object. We use the OGB featurization.
* The default smiles2graph requires rdkit to be installed *
"""
def __init__(self, root, max_ring_size, smiles2graph=smiles2graph,
transform=None, pre_transform=None, pre_filter=None,
include_down_adj=False, init_method='sum', n_jobs=2):
self.original_root = root
self.smiles2graph = smiles2graph
self.folder = osp.join(root, 'peptides-structural')
self.url = 'https://www.dropbox.com/s/464u3303eu2u4zp/peptide_structure_dataset.csv.gz?dl=1'
self.version = '9786061a34298a0684150f2e4ff13f47' # MD5 hash of the intended dataset file
self.url_stratified_split = 'https://www.dropbox.com/s/9dfifzft1hqgow6/splits_random_stratified_peptide_structure.pickle?dl=1'
self.md5sum_stratified_split = '5a0114bdadc80b94fc7ae974f13ef061'
# Check version and update if necessary.
release_tag = osp.join(self.folder, self.version)
if osp.isdir(self.folder) and (not osp.exists(release_tag)):
print(f"{self.__class__.__name__} has been updated.")
if input("Will you update the dataset now? (y/N)\n").lower() == 'y':
shutil.rmtree(self.folder)
self.name = 'peptides_structural'
self._max_ring_size = max_ring_size
self._use_edge_features = True
self._n_jobs = n_jobs
super(PeptidesStructuralDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim=2, init_method=init_method, include_down_adj=include_down_adj,
cellular=True, num_classes=1)
self.data, self.slices, idx, self.num_tasks = self.load_dataset()
self.train_ids = idx['train']
self.val_ids = idx['val']
self.test_ids = idx['test']
self.num_node_type = 9
self.num_edge_type = 3
@property
def raw_file_names(self):
return 'peptide_structure_dataset.csv.gz'
@property
def processed_file_names(self):
return [f'{self.name}_complex.pt', f'{self.name}_idx.pt', f'{self.name}_tasks.pt']
@property
def processed_dir(self):
"""Overwrite to change name based on edge and simple feats"""
directory = super(PeptidesStructuralDataset, self).processed_dir
suffix1 = f"_{self._max_ring_size}rings" if self._cellular else ""
suffix2 = "-E" if self._use_edge_features else ""
return directory + suffix1 + suffix2
def _md5sum(self, path):
hash_md5 = hashlib.md5()
with open(path, 'rb') as f:
buffer = f.read()
hash_md5.update(buffer)
return hash_md5.hexdigest()
def download(self):
if decide_download(self.url):
path = download_url(self.url, self.raw_dir)
# Save to disk the MD5 hash of the downloaded file.
hash = self._md5sum(path)
if hash != self.version:
raise ValueError("Unexpected MD5 hash of the downloaded file")
open(osp.join(self.root, hash), 'w').close()
# Download train/val/test splits.
path_split1 = download_url(self.url_stratified_split, self.root)
assert self._md5sum(path_split1) == self.md5sum_stratified_split
old_split_file = osp.join(self.root,
"splits_random_stratified_peptide_structure.pickle?dl=1")
new_split_file = osp.join(self.root,
"splits_random_stratified_peptide_structure.pickle")
old_df_name = osp.join(self.raw_dir,
'peptide_structure_dataset.csv.gz?dl=1')
new_df_name = osp.join(self.raw_dir,
'peptide_structure_dataset.csv.gz')
os.rename(old_split_file, new_split_file)
os.rename(old_df_name, new_df_name)
else:
print('Stop download.')
exit(-1)
def load_dataset(self):
"""Load the dataset from here and process it if it doesn't exist"""
print("Loading dataset from disk...")
data, slices = torch.load(self.processed_paths[0])
idx = torch.load(self.processed_paths[1])
tasks = torch.load(self.processed_paths[2])
return data, slices, idx, tasks
def process(self):
data_df = pd.read_csv(osp.join(self.raw_dir,
'peptide_structure_dataset.csv.gz'))
smiles_list = data_df['smiles']
target_names = ['Inertia_mass_a', 'Inertia_mass_b', 'Inertia_mass_c',
'Inertia_valence_a', 'Inertia_valence_b',
'Inertia_valence_c', 'length_a', 'length_b', 'length_c',
'Spherocity', 'Plane_best_fit']
# Normalize to zero mean and unit standard deviation.
data_df.loc[:, target_names] = data_df.loc[:, target_names].apply(
lambda x: (x - x.mean()) / x.std(), axis=0)
print('Converting SMILES strings into graphs...')
data_list = []
for i in tqdm(range(len(smiles_list))):
data = Data()
smiles = smiles_list[i]
y = data_df.iloc[i][target_names]
graph = self.smiles2graph(smiles)
assert (len(graph['edge_feat']) == graph['edge_index'].shape[1])
assert (len(graph['node_feat']) == graph['num_nodes'])
data.__num_nodes__ = int(graph['num_nodes'])
data.edge_index = torch.from_numpy(graph['edge_index']).to(
torch.int64)
data.edge_attr = torch.from_numpy(graph['edge_feat']).to(
torch.int64)
data.x = torch.from_numpy(graph['node_feat']).to(torch.int64)
data.y = torch.Tensor([y])
data_list.append(data)
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
split_idx = self.get_idx_split()
# NB: the init method would basically have no effect if
# we use edge features and do not initialize rings.
print(f"Converting the {self.name} dataset to a cell complex...")
complexes, _, _ = convert_graph_dataset_with_rings(
data_list,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_method=self._init_method,
init_edges=self._use_edge_features,
init_rings=False,
n_jobs=self._n_jobs)
print(f'Saving processed dataset in {self.processed_paths[0]}...')
torch.save(self.collate(complexes, self.max_dim), self.processed_paths[0])
print(f'Saving idx in {self.processed_paths[1]}...')
torch.save(split_idx, self.processed_paths[1])
print(f'Saving num_tasks in {self.processed_paths[2]}...')
torch.save(11, self.processed_paths[2])
def get_idx_split(self):
""" Get dataset splits.
Returns:
Dict with 'train', 'val', 'test', splits indices.
"""
split_file = osp.join(self.root,
"splits_random_stratified_peptide_structure.pickle")
with open(split_file, 'rb') as f:
splits = pickle.load(f)
split_dict = replace_numpy_with_torchtensor(splits)
split_dict['valid'] = split_dict['val']
return split_dict
def load_pep_s_graph_dataset(root):
raw_dir = osp.join(root, 'raw')
data_df = pd.read_csv(osp.join(raw_dir,
'peptide_structure_dataset.csv.gz'))
smiles_list = data_df['smiles']
target_names = ['Inertia_mass_a', 'Inertia_mass_b', 'Inertia_mass_c',
'Inertia_valence_a', 'Inertia_valence_b',
'Inertia_valence_c', 'length_a', 'length_b', 'length_c',
'Spherocity', 'Plane_best_fit']
# Normalize to zero mean and unit standard deviation.
data_df.loc[:, target_names] = data_df.loc[:, target_names].apply(
lambda x: (x - x.mean()) / x.std(), axis=0)
print('Converting SMILES strings into graphs...')
data_list = []
for i in tqdm(range(len(smiles_list))):
data = Data()
smiles = smiles_list[i]
y = data_df.iloc[i][target_names]
graph = smiles2graph(smiles)
assert (len(graph['edge_feat']) == graph['edge_index'].shape[1])
assert (len(graph['node_feat']) == graph['num_nodes'])
data.__num_nodes__ = int(graph['num_nodes'])
data.edge_index = torch.from_numpy(graph['edge_index']).to(
torch.int64)
data.edge_attr = torch.from_numpy(graph['edge_feat']).to(
torch.int64)
data.x = torch.from_numpy(graph['node_feat']).to(torch.int64)
data.y = torch.Tensor([y])
data_list.append(data)
dataset = InMemoryDataset.collate(data_list)
#get split file
split_file = osp.join(root,
"splits_random_stratified_peptide_structure.pickle")
with open(split_file, 'rb') as f:
splits = pickle.load(f)
split_dict = replace_numpy_with_torchtensor(splits)
split_dict['valid'] = split_dict['val']
return dataset, split_dict['train'], split_dict['valid'], split_dict['test'] | 11,359 | 41.546816 | 134 | py |
cwn | cwn-main/data/datasets/peptides_functional.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 2 21:37:42 2023
@author: renz
"""
import hashlib
import os.path as osp
import os
import pickle
import shutil
import pandas as pd
import torch
from ogb.utils import smiles2graph
from ogb.utils.torch_util import replace_numpy_with_torchtensor
from ogb.utils.url import decide_download
from torch_geometric.data import Data, download_url
from torch_geometric.data import InMemoryDataset
from data.utils import convert_graph_dataset_with_rings
from data.datasets import InMemoryComplexDataset
from tqdm import tqdm
class PeptidesFunctionalDataset(InMemoryComplexDataset):
"""
PyG dataset of 15,535 peptides represented as their molecular graph
(SMILES) with 10-way multi-task binary classification of their
functional classes.
The goal is use the molecular representation of peptides instead
of amino acid sequence representation ('peptide_seq' field in the file,
provided for possible baseline benchmarking but not used here) to test
GNNs' representation capability.
The 10 classes represent the following functional classes (in order):
['antifungal', 'cell_cell_communication', 'anticancer',
'drug_delivery_vehicle', 'antimicrobial', 'antiviral',
'antihypertensive', 'antibacterial', 'antiparasitic', 'toxic']
Args:
root (string): Root directory where the dataset should be saved.
smiles2graph (callable): A callable function that converts a SMILES
string into a graph object. We use the OGB featurization.
* The default smiles2graph requires rdkit to be installed *
"""
def __init__(self, root, max_ring_size, smiles2graph=smiles2graph,
transform=None, pre_transform=None, pre_filter=None,
include_down_adj=False, init_method='sum', n_jobs=2):
self.original_root = root
self.smiles2graph = smiles2graph
self.folder = osp.join(root, 'peptides-functional')
self.url = 'https://www.dropbox.com/s/ol2v01usvaxbsr8/peptide_multi_class_dataset.csv.gz?dl=1'
self.version = '701eb743e899f4d793f0e13c8fa5a1b4' # MD5 hash of the intended dataset file
self.url_stratified_split = 'https://www.dropbox.com/s/j4zcnx2eipuo0xz/splits_random_stratified_peptide.pickle?dl=1'
self.md5sum_stratified_split = '5a0114bdadc80b94fc7ae974f13ef061'
# Check version and update if necessary.
release_tag = osp.join(self.folder, self.version)
if osp.isdir(self.folder) and (not osp.exists(release_tag)):
print(f"{self.__class__.__name__} has been updated.")
if input("Will you update the dataset now? (y/N)\n").lower() == 'y':
shutil.rmtree(self.folder)
self.name = 'peptides_functional'
self._max_ring_size = max_ring_size
self._use_edge_features = True
self._n_jobs = n_jobs
super(PeptidesFunctionalDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim=2, init_method=init_method, include_down_adj=include_down_adj,
cellular=True, num_classes=1)
self.data, self.slices, idx, self.num_tasks = self.load_dataset()
self.train_ids = idx['train']
self.val_ids = idx['val']
self.test_ids = idx['test']
self.num_node_type = 9
self.num_edge_type = 3
@property
def raw_file_names(self):
return 'peptide_multi_class_dataset.csv.gz'
@property
def processed_file_names(self):
return [f'{self.name}_complex.pt', f'{self.name}_idx.pt', f'{self.name}_tasks.pt']
@property
def processed_dir(self):
"""Overwrite to change name based on edge and simple feats"""
directory = super(PeptidesFunctionalDataset, self).processed_dir
suffix1 = f"_{self._max_ring_size}rings" if self._cellular else ""
suffix2 = "-E" if self._use_edge_features else ""
return directory + suffix1 + suffix2
def _md5sum(self, path):
hash_md5 = hashlib.md5()
with open(path, 'rb') as f:
buffer = f.read()
hash_md5.update(buffer)
return hash_md5.hexdigest()
def download(self):
if decide_download(self.url):
path = download_url(self.url, self.raw_dir)
# Save to disk the MD5 hash of the downloaded file.
hash = self._md5sum(path)
if hash != self.version:
raise ValueError("Unexpected MD5 hash of the downloaded file")
open(osp.join(self.root, hash), 'w').close()
# Download train/val/test splits.
path_split1 = download_url(self.url_stratified_split, self.root)
assert self._md5sum(path_split1) == self.md5sum_stratified_split
old_df_name = osp.join(self.raw_dir,
'peptide_multi_class_dataset.csv.gz?dl=1')
new_df_name = osp.join(self.raw_dir,
'peptide_multi_class_dataset.csv.gz')
old_split_file = osp.join(self.root,
"splits_random_stratified_peptide.pickle?dl=1")
new_split_file = osp.join(self.root,
"splits_random_stratified_peptide.pickle")
os.rename(old_df_name, new_df_name)
os.rename(old_split_file, new_split_file)
else:
print('Stop download.')
exit(-1)
def load_dataset(self):
"""Load the dataset from here and process it if it doesn't exist"""
print("Loading dataset from disk...")
data, slices = torch.load(self.processed_paths[0])
idx = torch.load(self.processed_paths[1])
tasks = torch.load(self.processed_paths[2])
return data, slices, idx, tasks
def process(self):
data_df = pd.read_csv(osp.join(self.raw_dir,
'peptide_multi_class_dataset.csv.gz'))
smiles_list = data_df['smiles']
print('Converting SMILES strings into graphs...')
data_list = []
for i in tqdm(range(len(smiles_list))):
data = Data()
smiles = smiles_list[i]
graph = self.smiles2graph(smiles)
assert (len(graph['edge_feat']) == graph['edge_index'].shape[1])
assert (len(graph['node_feat']) == graph['num_nodes'])
data.__num_nodes__ = int(graph['num_nodes'])
data.edge_index = torch.from_numpy(graph['edge_index']).to(
torch.int64)
data.edge_attr = torch.from_numpy(graph['edge_feat']).to(
torch.int64)
data.x = torch.from_numpy(graph['node_feat']).to(torch.int64)
data.y = torch.Tensor([eval(data_df['labels'].iloc[i])])
data_list.append(data)
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
split_idx = self.get_idx_split()
# NB: the init method would basically have no effect if
# we use edge features and do not initialize rings.
print(f"Converting the {self.name} dataset to a cell complex...")
complexes, _, _ = convert_graph_dataset_with_rings(
data_list,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_method=self._init_method,
init_edges=self._use_edge_features,
init_rings=False,
n_jobs=self._n_jobs)
print(f'Saving processed dataset in {self.processed_paths[0]}...')
torch.save(self.collate(complexes, self.max_dim), self.processed_paths[0])
print(f'Saving idx in {self.processed_paths[1]}...')
torch.save(split_idx, self.processed_paths[1])
print(f'Saving num_tasks in {self.processed_paths[2]}...')
torch.save(10, self.processed_paths[2])
def get_idx_split(self):
""" Get dataset splits.
Returns:
Dict with 'train', 'val', 'test', splits indices.
"""
split_file = osp.join(self.root,
"splits_random_stratified_peptide.pickle")
with open(split_file, 'rb') as f:
splits = pickle.load(f)
split_dict = replace_numpy_with_torchtensor(splits)
split_dict['valid'] = split_dict['val']
return split_dict
def load_pep_f_graph_dataset(root):
raw_dir = osp.join(root, 'raw')
data_df = pd.read_csv(osp.join(raw_dir,
'peptide_multi_class_dataset.csv.gz'))
smiles_list = data_df['smiles']
target_names = ['Inertia_mass_a', 'Inertia_mass_b', 'Inertia_mass_c',
'Inertia_valence_a', 'Inertia_valence_b',
'Inertia_valence_c', 'length_a', 'length_b', 'length_c',
'Spherocity', 'Plane_best_fit']
# Normalize to zero mean and unit standard deviation.
data_df.loc[:, target_names] = data_df.loc[:, target_names].apply(
lambda x: (x - x.mean()) / x.std(), axis=0)
print('Converting SMILES strings into graphs...')
data_list = []
for i in tqdm(range(len(smiles_list))):
data = Data()
smiles = smiles_list[i]
y = data_df.iloc[i][target_names]
graph = smiles2graph(smiles)
assert (len(graph['edge_feat']) == graph['edge_index'].shape[1])
assert (len(graph['node_feat']) == graph['num_nodes'])
data.__num_nodes__ = int(graph['num_nodes'])
data.edge_index = torch.from_numpy(graph['edge_index']).to(
torch.int64)
data.edge_attr = torch.from_numpy(graph['edge_feat']).to(
torch.int64)
data.x = torch.from_numpy(graph['node_feat']).to(torch.int64)
data.y = torch.Tensor([y])
data_list.append(data)
dataset = InMemoryDataset.collate(data_list)
#get split file
split_file = osp.join(root,
"splits_random_stratified_peptide.pickle")
with open(split_file, 'rb') as f:
splits = pickle.load(f)
split_dict = replace_numpy_with_torchtensor(splits)
split_dict['valid'] = split_dict['val']
return dataset, split_dict['train'], split_dict['valid'], split_dict['test'] | 10,424 | 39.564202 | 124 | py |
cwn | cwn-main/data/datasets/ocean.py | import pickle
import os.path as osp
from data.datasets import InMemoryComplexDataset
from data.datasets.ocean_utils import load_ocean_dataset
# TODO: Set up a cochain dataset structure or make complex dataset better support cochain-only data.
# TODO: Refactor the dataset to use the latest storage formatting.
class OceanDataset(InMemoryComplexDataset):
"""A real-world dataset for edge-flow classification.
The dataset is adapted from https://arxiv.org/abs/1807.05044
"""
def __init__(self, root, name, load_graph=False, train_orient='default',
test_orient='default'):
self.name = name
self._num_classes = 2
self._train_orient = train_orient
self._test_orient = test_orient
super(OceanDataset, self).__init__(root, max_dim=1,
num_classes=self._num_classes, include_down_adj=True)
with open(self.processed_paths[0], 'rb') as handle:
train = pickle.load(handle)
with open(self.processed_paths[1], 'rb') as handle:
val = pickle.load(handle)
self.__data_list__ = train + val
self.G = None
if load_graph:
with open(self.processed_paths[2], 'rb') as handle:
self.G = pickle.load(handle)
self.train_ids = list(range(len(train)))
self.val_ids = list(range(len(train), len(train) + len(val)))
self.test_ids = None
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
return osp.join(self.root, f'complex_{self._train_orient}_{self._test_orient}')
@property
def processed_file_names(self):
return ['train_{}_complex_list.pkl'.format(self.name),
'val_{}_complex_list.pkl'.format(self.name),
'{}_graph.pkl'.format(self.name)]
def process(self):
train, val, G = load_ocean_dataset(self._train_orient, self._test_orient)
train_path = self.processed_paths[0]
print(f"Saving train dataset to {train_path}")
with open(train_path, 'wb') as handle:
pickle.dump(train, handle)
val_path = self.processed_paths[1]
print(f"Saving val dataset to {val_path}")
with open(val_path, 'wb') as handle:
pickle.dump(val, handle)
graph_path = self.processed_paths[2]
with open(graph_path, 'wb') as handle:
pickle.dump(G, handle)
def len(self):
"""Override method to make the class work with deprecated stoarage"""
return len(self.__data_list__)
| 2,602 | 34.175676 | 100 | py |
cwn | cwn-main/data/datasets/plot_ringtree_dataset.py | import networkx as nx
import matplotlib.pyplot as plt
from data.datasets.ring_utils import generate_ring_transfer_graph_dataset
from torch_geometric.utils import convert
def visualise_ringtree_dataset():
dataset = generate_ring_transfer_graph_dataset(nodes=10, samples=100, classes=5)
data = dataset[0]
graph = convert.to_networkx(data, to_undirected=True)
plt.figure()
nx.draw_networkx(graph)
plt.show()
if __name__ == "__main__":
visualise_ringtree_dataset()
| 495 | 23.8 | 84 | py |
cwn | cwn-main/data/datasets/test_ringtransfer.py | import os.path as osp
from data.datasets.ring_utils import generate_ring_transfer_graph_dataset
from data.utils import convert_graph_dataset_with_rings
from data.datasets import RingTransferDataset
from definitions import ROOT_DIR
def test_ringtree_dataset_generation():
dataset = generate_ring_transfer_graph_dataset(nodes=10, samples=100, classes=5)
labels = dict()
for data in dataset:
assert data.edge_index[0].min() == 0
assert data.edge_index[1].min() == 0
assert data.edge_index[0].max() == 9
assert data.edge_index[1].max() == 9
assert data.x.size(0) == 10
assert data.x.size(1) == 5
label = data.y.item()
if label not in labels:
labels[label] = 0
labels[label] += 1
assert list(range(5)) == list(sorted(labels.keys()))
assert {20} == set(labels.values())
def test_ringtree_dataset_conversion():
dataset = generate_ring_transfer_graph_dataset(nodes=10, samples=10, classes=5)
complexes, _, _ = convert_graph_dataset_with_rings(dataset, max_ring_size=10,
include_down_adj=False, init_rings=True)
for complex in complexes:
assert 2 in complex.cochains
assert complex.cochains[2].num_cells == 1
assert complex.cochains[1].num_cells == 10
assert complex.cochains[0].num_cells == 10
assert complex.nodes.x.size(0) == 10
assert complex.nodes.x.size(1) == 5
assert complex.edges.x.size(0) == 10
assert complex.edges.x.size(1) == 5
assert complex.two_cells.x.size(0) == 1
assert complex.two_cells.x.size(1) == 5
def test_ring_transfer_dataset_loading():
# Test everything runs without errors.
root = osp.join(ROOT_DIR, 'datasets', 'RING-TRANSFER')
dataset = RingTransferDataset(root=root, train=20, test=10)
dataset.get(0)
| 1,900 | 35.557692 | 95 | py |
cwn | cwn-main/data/datasets/cluster.py | import pickle
from data.datasets import InMemoryComplexDataset
from data.utils import convert_graph_dataset_with_gudhi
from torch_geometric.datasets import GNNBenchmarkDataset
class ClusterDataset(InMemoryComplexDataset):
"""This is the Cluster dataset from the Benchmarking GNNs paper.
The dataset contains multiple graphs and we have to do node classification on all these graphs.
"""
def __init__(self, root, transform=None,
pre_transform=None, pre_filter=None, max_dim=2):
self.name = 'CLUSTER'
super(ClusterDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim=max_dim)
self.max_dim = max_dim
self._data_list, idx = self.load_dataset()
self.train_ids = idx[0]
self.val_ids = idx[1]
self.test_ids = idx[2]
@property
def raw_file_names(self):
name = self.name
# The processed graph files are our raw files.
# I've obtained this from inside the GNNBenchmarkDataset class
return [f'{name}_train.pt', f'{name}_val.pt', f'{name}_test.pt']
@property
def processed_file_names(self):
return ['complex_train.pkl', 'complex_val.pkl', 'complex_test.pkl']
def download(self):
# Instantiating this will download and process the graph dataset.
GNNBenchmarkDataset('./datasets/', 'CLUSTER')
def load_dataset(self):
"""Load the dataset from here and process it if it doesn't exist"""
data_list, idx = [], []
start = 0
for path in self.processed_paths:
with open(path, 'rb') as handle:
data_list.extend(pickle.load(handle))
idx.append(list(range(start, len(data_list))))
start = len(data_list)
return data_list, idx
def process(self):
# At this stage, the graph dataset is already downloaded and processed
print(f"Processing cellular complex dataset for {self.name}")
train_data = GNNBenchmarkDataset('./datasets/', 'CLUSTER', split='train')
val_data = GNNBenchmarkDataset('./datasets/', 'CLUSTER', split='val')
test_data = GNNBenchmarkDataset('./datasets/', 'CLUSTER', split='test')
# For testing
# train_data = list(train_data)[:3]
# val_data = list(val_data)[:3]
# test_data = list(test_data)[:3]
print("Converting the train dataset with gudhi...")
train_complexes, _, _ = convert_graph_dataset_with_gudhi(train_data,
expansion_dim=self.max_dim, include_down_adj=self.include_down_adj)
print("Converting the validation dataset with gudhi...")
val_complexes, _, _ = convert_graph_dataset_with_gudhi(val_data, expansion_dim=self.max_dim, include_down_adj=self.include_down_adj)
print("Converting the test dataset with gudhi...")
test_complexes, _, _ = convert_graph_dataset_with_gudhi(test_data,
expansion_dim=self.max_dim)
complexes = [train_complexes, val_complexes, test_complexes]
for i, path in enumerate(self.processed_paths):
with open(path, 'wb') as handle:
pickle.dump(complexes[i], handle)
| 3,283 | 41.102564 | 140 | py |
cwn | cwn-main/data/datasets/csl.py | import os.path as osp
import numpy as np
import torch
from data.datasets import InMemoryComplexDataset
from data.utils import convert_graph_dataset_with_rings
from torch_geometric.datasets import GNNBenchmarkDataset
from torch_geometric.utils import remove_self_loops
class CSLDataset(InMemoryComplexDataset):
"""This is the CSL (Circular Skip Link) dataset from the Benchmarking GNNs paper.
The dataset contains 10 isomorphism classes of regular graphs that must be classified.
"""
def __init__(self, root, transform=None,
pre_transform=None, pre_filter=None, max_ring_size=6, fold=0, init_method='sum',
n_jobs=2):
self.name = 'CSL'
self._max_ring_size = max_ring_size
self._n_jobs = n_jobs
super(CSLDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim=2, cellular=True, init_method=init_method,
num_classes=10)
assert 0 <= fold <= 4
self.fold = fold
self.data, self.slices = self.load_dataset()
self.num_node_type = 1
self.num_edge_type = 1
# These cross-validation splits have been taken from
# https://github.com/graphdeeplearning/benchmarking-gnns/tree/master/data/CSL
train_filename = osp.join(self.root, 'splits', 'CSL_train.txt')
valid_filename = osp.join(self.root, 'splits', 'CSL_val.txt')
test_filename = osp.join(self.root, 'splits', 'CSL_test.txt')
self.train_ids = np.loadtxt(train_filename, dtype=int, delimiter=',')[fold].tolist()
self.val_ids = np.loadtxt(valid_filename, dtype=int, delimiter=',')[fold].tolist()
self.test_ids = np.loadtxt(test_filename, dtype=int, delimiter=',')[fold].tolist()
# Make sure the split ratios are as expected (3:1:1)
assert len(self.train_ids) == 3 * len(self.test_ids)
assert len(self.val_ids) == len(self.test_ids)
# Check all splits contain numbers that are smaller than the total number of graphs
assert max(self.train_ids) < 150
assert max(self.val_ids) < 150
assert max(self.test_ids) < 150
@property
def raw_file_names(self):
return ['data.pt']
@property
def processed_file_names(self):
return ['complexes.pt']
def download(self):
# Instantiating this will download and process the graph dataset.
GNNBenchmarkDataset(self.raw_dir, 'CSL')
def load_dataset(self):
"""Load the dataset from here and process it if it doesn't exist"""
print("Loading dataset from disk...")
data, slices = torch.load(self.processed_paths[0])
return data, slices
def process(self):
# At this stage, the graph dataset is already downloaded and processed
print(f"Processing cell complex dataset for {self.name}")
# This dataset has no train / val / test splits and we must use cross-validation
data = GNNBenchmarkDataset(self.raw_dir, 'CSL')
assert len(data) == 150
# Check that indeed there are no features
assert data[0].x is None
assert data[0].edge_attr is None
print("Populating graph with features")
# Initialise everything with zero as in the Benchmarking GNNs code
# https://github.com/graphdeeplearning/benchmarking-gnns/blob/ef8bd8c7d2c87948bc1bdd44099a52036e715cd0/data/CSL.py#L144
new_data = []
for i, datum in enumerate(data):
edge_index = datum.edge_index
num_nodes = datum.num_nodes
# Make sure we have no self-loops in this dataset
edge_index, _ = remove_self_loops(edge_index)
num_edges = edge_index.size(1)
vx = torch.zeros((num_nodes, 1), dtype=torch.long)
edge_attr = torch.zeros(num_edges, dtype=torch.long)
setattr(datum, 'edge_index', edge_index)
setattr(datum, 'x', vx)
setattr(datum, 'edge_attr', edge_attr)
new_data.append(datum)
assert new_data[0].x is not None
assert new_data[0].edge_attr is not None
print("Converting the train dataset to a cell complex...")
complexes, _, _ = convert_graph_dataset_with_rings(
new_data,
max_ring_size=self._max_ring_size,
include_down_adj=False,
init_edges=True,
init_rings=False,
n_jobs=self._n_jobs)
path = self.processed_paths[0]
print(f'Saving processed dataset in {path}....')
torch.save(self.collate(complexes, 2), path)
@property
def processed_dir(self):
"""Overwrite to change name based on edges"""
directory = super(CSLDataset, self).processed_dir
suffix1 = f"_{self._max_ring_size}rings" if self._cellular else ""
return directory + suffix1
| 4,912 | 39.270492 | 127 | py |
cwn | cwn-main/data/datasets/flow.py | import pickle
import os.path as osp
from data.datasets import InMemoryComplexDataset
from data.datasets.flow_utils import load_flow_dataset
# TODO: Set up a cochain dataset structure or make complex dataset better support cochain-only data.
# TODO: Make this dataset use the new storage system.
class FlowDataset(InMemoryComplexDataset):
"""A synthetic dataset for edge-flow classification."""
def __init__(self, root, name, num_points, train_samples, val_samples,
load_graph=False, train_orient='default', test_orient='default', n_jobs=2):
self.name = name
self._num_classes = 2
self._num_points = num_points
self._train_samples = train_samples
self._val_samples = val_samples
self._train_orient = train_orient
self._test_orient = test_orient
self._n_jobs = n_jobs
super(FlowDataset, self).__init__(root, max_dim=1,
num_classes=self._num_classes, include_down_adj=True)
with open(self.processed_paths[0], 'rb') as handle:
self.__data_list__ = pickle.load(handle)
self.G = None
if load_graph:
with open(self.processed_paths[1], 'rb') as handle:
self.G = pickle.load(handle)
self.train_ids = list(range(train_samples))
self.val_ids = list(range(train_samples, train_samples + val_samples))
self.test_ids = None
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
return osp.join(self.root,
f'flow{self._num_points}_orient_{self._train_orient}_{self._test_orient}')
@property
def processed_file_names(self):
return ['{}_complex_list.pkl'.format(self.name), '{}_graph.pkl'.format(self.name)]
def process(self):
train, val, G = load_flow_dataset(num_points=self._num_points,
num_train=self._train_samples, num_test=self._val_samples,
train_orientation=self._train_orient, test_orientation=self._test_orient,
n_jobs=self._n_jobs)
cochains = train + val
path = self.processed_paths[0]
print(f"Saving dataset in {path}...")
with open(path, 'wb') as handle:
pickle.dump(cochains, handle)
graph_path = self.processed_paths[1]
with open(graph_path, 'wb') as handle:
pickle.dump(G, handle)
@property
def raw_file_names(self):
return ""
def download(self):
pass
def len(self):
"""Override method to make the class work with deprecated stoarage"""
return len(self.__data_list__)
| 2,666 | 34.56 | 100 | py |
cwn | cwn-main/data/datasets/flow_utils.py | import numpy as np
import random
import torch
import networkx as nx
import itertools
from scipy.spatial import Delaunay
from scipy import sparse
from data.complex import Cochain
from data.parallel import ProgressParallel
from joblib import delayed
def is_inside_rectangle(x, rect):
return rect[0, 0] <= x[0] <= rect[1, 0] and rect[0, 1] <= x[1] <= rect[1, 1]
def sample_point_from_rect(points, rect):
samples = []
for i in range(len(points)):
if is_inside_rectangle(points[i], rect):
samples.append(i)
return random.choice(samples)
def create_hole(points, triangles, hole):
kept_triangles = []
removed_vertices = set()
# Find the points and triangles to remove
for i in range(len(triangles)):
simplex = triangles[i]
assert len(simplex) == 3
xs = points[simplex]
remove_triangle = False
for j in range(3):
vertex = simplex[j]
if is_inside_rectangle(xs[j], hole):
remove_triangle = True
removed_vertices.add(vertex)
if not remove_triangle:
kept_triangles.append(i)
# Remove the triangles and points inside the holes
triangles = triangles[np.array(kept_triangles)]
# Remove the points that are not part of any triangles anymore.
# This can happen in some very rare cases
for i in range(len(points)):
if np.sum(triangles == i) == 0:
removed_vertices.add(i)
points = np.delete(points, list(removed_vertices), axis=0)
# Renumber the indices of the triangles' vertices
for vertex in sorted(removed_vertices, reverse=True):
triangles[triangles >= vertex] -= 1
return points, triangles
def create_graph_from_triangulation(points, triangles):
# Create a graph from from this containing only the non-removed triangles
G = nx.Graph()
edge_idx = 0
edge_to_tuple = {}
tuple_to_edge = {}
for i in range(len(triangles)):
vertices = triangles[i]
for j in range(3):
if vertices[j] not in G:
G.add_node(vertices[j], point=points[vertices[j]])
for v1, v2 in itertools.combinations(vertices, 2):
if not G.has_edge(v1, v2):
G.add_edge(v1, v2, index=edge_idx)
edge_to_tuple[edge_idx] = (min(v1, v2), max(v1, v2))
tuple_to_edge[(min(v1, v2), max(v1, v2))] = edge_idx
edge_idx += 1
assert G.has_edge(v2, v1)
G.graph['edge_to_tuple'] = edge_to_tuple
G.graph['tuple_to_edge'] = tuple_to_edge
G.graph['points'] = points
G.graph['triangles'] = triangles
return G
def extract_boundary_matrices(G: nx.Graph):
"""Compute the boundary and co-boundary matrices for the edges of the complex. """
edge_to_tuple = G.graph['edge_to_tuple']
tuple_to_edge = G.graph['tuple_to_edge']
triangles = G.graph['triangles']
B1 = np.zeros((G.number_of_nodes(), G.number_of_edges()), dtype=float)
for edge_id in range(G.number_of_edges()):
nodes = edge_to_tuple[edge_id]
min_node = min(nodes)
max_node = max(nodes)
B1[min_node, edge_id] = -1
B1[max_node, edge_id] = 1
assert np.all(np.sum(np.abs(B1), axis=-1) > 0)
assert np.all(np.sum(np.abs(B1), axis=0) == 2)
assert np.all(np.sum(B1, axis=0) == 0)
def extract_edge_and_orientation(triangle, i):
assert i <= 2
n1 = triangle[i]
if i < 2:
n2 = triangle[i + 1]
else:
n2 = triangle[0]
if n1 < n2:
orientation = 1
else:
orientation = -1
return tuple_to_edge[(min(n1, n2), max(n1, n2))], orientation
B2 = np.zeros((G.number_of_edges(), len(triangles)), dtype=float)
for i in range(len(triangles)):
edge1, orientation1 = extract_edge_and_orientation(triangles[i], 0)
edge2, orientation2 = extract_edge_and_orientation(triangles[i], 1)
edge3, orientation3 = extract_edge_and_orientation(triangles[i], 2)
assert edge1 != edge2 and edge1 != edge3 and edge2 != edge3
B2[edge1, i] = orientation1
B2[edge2, i] = orientation2
B2[edge3, i] = orientation3
assert np.all(np.sum(np.abs(B2), axis=0) == 3)
assert np.all(np.sum(np.abs(B2), axis=-1) > 0)
return B1, B2
def generate_trajectory(start_rect, end_rect, ckpt_rect, G: nx.Graph):
points = G.graph['points']
tuple_to_edge = G.graph['tuple_to_edge']
start_vertex = sample_point_from_rect(points, start_rect)
end_vertex = sample_point_from_rect(points, end_rect)
ckpt_vertex = sample_point_from_rect(points, ckpt_rect)
x = np.zeros((len(tuple_to_edge), 1))
vertex = start_vertex
end_point = points[end_vertex]
ckpt_point = points[ckpt_vertex]
path = [vertex]
explored = set()
ckpt_reached = False
while vertex != end_vertex:
explored.add(vertex)
if vertex == ckpt_vertex:
ckpt_reached = True
nv = np.array([nghb for nghb in G.neighbors(vertex)
if nghb not in explored])
if len(nv) == 0:
# If we get stuck because everything around was explored
# Then just try to generate another trajectory.
return generate_trajectory(start_rect, end_rect, ckpt_rect, G)
npoints = points[nv]
if ckpt_reached:
dist = np.sum((npoints - end_point[None, :]) ** 2, axis=-1)
else:
dist = np.sum((npoints - ckpt_point[None, :]) ** 2, axis=-1)
# prob = softmax(-dist**2)
# vertex = nv[np.random.choice(len(prob), p=prob)]
coin_toss = np.random.uniform()
if coin_toss < 0.1:
vertex = nv[np.random.choice(len(dist))]
else:
vertex = nv[np.argmin(dist)]
path.append(vertex)
# Set the flow value according to the orientation
if path[-2] < path[-1]:
x[tuple_to_edge[(path[-2], path[-1])], 0] = 1
else:
x[tuple_to_edge[(path[-1], path[-2])], 0] = -1
return x, path
def extract_adj_from_boundary(B, G=None):
A = sparse.csr_matrix(B.T).dot(sparse.csr_matrix(B))
n = A.shape[0]
if G is not None:
assert n == G.number_of_edges()
# Subtract self-loops, which we do not count.
connections = A.count_nonzero() - np.sum(A.diagonal() != 0)
index = torch.empty((2, connections), dtype=torch.long)
orient = torch.empty(connections)
connection = 0
cA = A.tocoo()
for i, j, v in zip(cA.row, cA.col, cA.data):
if j >= i:
continue
assert v == 1 or v == -1, print(v)
index[0, connection] = i
index[1, connection] = j
orient[connection] = np.sign(v)
index[0, connection + 1] = j
index[1, connection + 1] = i
orient[connection + 1] = np.sign(v)
connection += 2
assert connection == connections
return index, orient
def build_cochain(B1, B2, T2, x, class_id, G=None):
# Change the orientation of the boundary matrices
B1 = sparse.csr_matrix(B1).dot(sparse.csr_matrix(T2)).toarray()
B2 = sparse.csr_matrix(T2).dot(sparse.csr_matrix(B2)).toarray()
# Extract the adjacencies in pyG edge_index format.
lower_index, lower_orient = extract_adj_from_boundary(B1, G)
upper_index, upper_orient = extract_adj_from_boundary(B2.T, G)
index_dict = {
'lower_index': lower_index,
'lower_orient': lower_orient,
'upper_index': upper_index,
'upper_orient': upper_orient,
}
# Change the orientation of the features
x = sparse.csr_matrix(T2).dot(sparse.csr_matrix(x)).toarray()
x = torch.tensor(x, dtype=torch.float32)
return Cochain(dim=1, x=x, **index_dict, y=torch.tensor([class_id]))
def generate_flow_cochain(class_id, G, B1, B2, T2):
assert 0 <= class_id <= 1
# Define the start, midpoint and and stop regions for the trajectories.
start_rect = np.array([[0.0, 0.8], [0.2, 1.0]])
end_rect = np.array([[0.8, 0.0], [1.0, 0.2]])
bot_ckpt_rect = np.array([[0.0, 0.0], [0.2, 0.2]])
top_ckpt_rect = np.array([[0.8, 0.8], [1.0, 1.0]])
ckpts = [bot_ckpt_rect, top_ckpt_rect]
# Generate flow
x, _ = generate_trajectory(start_rect, end_rect, ckpts[class_id], G)
return build_cochain(B1, B2, T2, x, class_id, G)
def get_orient_matrix(size, orientation):
"""Creates a change of orientation operator of the specified size."""
if orientation == 'default':
return np.identity(size)
elif orientation == 'random':
diag = 2*np.random.randint(0, 2, size=size) - 1
return np.diag(diag).astype(np.long)
else:
raise ValueError(f'Unsupported orientation {orientation}')
def load_flow_dataset(num_points=1000, num_train=1000, num_test=200,
train_orientation='default', test_orientation='default', n_jobs=2):
points = np.random.uniform(low=-0.05, high=1.05, size=(num_points, 2))
tri = Delaunay(points)
# Double check each point appears in some triangle.
for i in range(len(points)):
assert np.sum(tri.simplices == i) > 0
hole1 = np.array([[0.2, 0.2], [0.4, 0.4]])
hole2 = np.array([[0.6, 0.6], [0.8, 0.8]])
points, triangles = create_hole(points, tri.simplices, hole1)
# Double check each point appears in some triangle.
for i in range(len(points)):
assert np.sum(triangles == i) > 0
points, triangles = create_hole(points, triangles, hole2)
# Double check each point appears in some triangle.
for i in range(len(points)):
assert np.sum(triangles == i) > 0
assert np.min(triangles) == 0
assert np.max(triangles) == len(points) - 1
G = create_graph_from_triangulation(points, triangles)
assert G.number_of_nodes() == len(points)
B1, B2 = extract_boundary_matrices(G)
classes = 2
assert B1.shape[1] == B2.shape[0]
num_edges = B1.shape[1]
# Process these in parallel because it's slow
samples_per_class = num_train // classes
parallel = ProgressParallel(n_jobs=n_jobs, use_tqdm=True, total=num_train)
train_samples = parallel(delayed(generate_flow_cochain)(
class_id=min(i // samples_per_class, 1), G=G, B1=B1, B2=B2,
T2=get_orient_matrix(num_edges, train_orientation)) for i in range(num_train))
samples_per_class = num_test // classes
parallel = ProgressParallel(n_jobs=n_jobs, use_tqdm=True, total=num_test)
test_samples = parallel(delayed(generate_flow_cochain)(
class_id=min(i // samples_per_class, 1), G=G, B1=B1, B2=B2,
T2=get_orient_matrix(num_edges, test_orientation)) for i in range(num_test))
return train_samples, test_samples, G
| 10,807 | 30.976331 | 89 | py |
cwn | cwn-main/data/datasets/sr.py | import os
import torch
import pickle
from data.sr_utils import load_sr_dataset
from data.utils import compute_clique_complex_with_gudhi, compute_ring_2complex
from data.utils import convert_graph_dataset_with_rings, convert_graph_dataset_with_gudhi
from data.datasets import InMemoryComplexDataset
from definitions import ROOT_DIR
from torch_geometric.data import Data
import os.path as osp
import errno
def makedirs(path):
try:
os.makedirs(osp.expanduser(osp.normpath(path)))
except OSError as e:
if e.errno != errno.EEXIST and osp.isdir(path):
raise e
def load_sr_graph_dataset(name, root=os.path.join(ROOT_DIR, 'datasets'), prefer_pkl=False):
raw_dir = os.path.join(root, 'SR_graphs', 'raw')
load_from = os.path.join(raw_dir, '{}.g6'.format(name))
load_from_pkl = os.path.join(raw_dir, '{}.pkl'.format(name))
if prefer_pkl and osp.exists(load_from_pkl):
print(f"Loading SR graph {name} from pickle dump...")
with open(load_from_pkl, 'rb') as handle:
data = pickle.load(handle)
else:
data = load_sr_dataset(load_from)
graphs = list()
for datum in data:
edge_index, num_nodes = datum
x = torch.ones(num_nodes, 1, dtype=torch.float32)
graph = Data(x=x, edge_index=edge_index, y=None, edge_attr=None, num_nodes=num_nodes)
graphs.append(graph)
train_ids = list(range(len(graphs)))
val_ids = list(range(len(graphs)))
test_ids = list(range(len(graphs)))
return graphs, train_ids, val_ids, test_ids
class SRDataset(InMemoryComplexDataset):
"""A dataset of complexes obtained by lifting Strongly Regular graphs."""
def __init__(self, root, name, max_dim=2, num_classes=16, train_ids=None, val_ids=None, test_ids=None,
include_down_adj=False, max_ring_size=None, n_jobs=2, init_method='sum'):
self.name = name
self._num_classes = num_classes
self._n_jobs = n_jobs
assert max_ring_size is None or max_ring_size > 3
self._max_ring_size = max_ring_size
cellular = (max_ring_size is not None)
if cellular:
assert max_dim == 2
super(SRDataset, self).__init__(root, max_dim=max_dim, num_classes=num_classes,
include_down_adj=include_down_adj, cellular=cellular, init_method=init_method)
self.data, self.slices = torch.load(self.processed_paths[0])
self.train_ids = list(range(self.len())) if train_ids is None else train_ids
self.val_ids = list(range(self.len())) if val_ids is None else val_ids
self.test_ids = list(range(self.len())) if test_ids is None else test_ids
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
directory = super(SRDataset, self).processed_dir
suffix = f"_{self._max_ring_size}rings" if self._cellular else ""
suffix += f"_down_adj" if self.include_down_adj else ""
return directory + suffix
@property
def processed_file_names(self):
return ['{}_complex_list.pt'.format(self.name)]
def process(self):
graphs, _, _, _ = load_sr_graph_dataset(self.name, prefer_pkl=True)
exp_dim = self.max_dim
if self._cellular:
print(f"Converting the {self.name} dataset to a cell complex...")
complexes, max_dim, num_features = convert_graph_dataset_with_rings(
graphs,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_method=self._init_method,
init_edges=True,
init_rings=True,
n_jobs=self._n_jobs)
else:
print(f"Converting the {self.name} dataset with gudhi...")
complexes, max_dim, num_features = convert_graph_dataset_with_gudhi(
graphs,
expansion_dim=exp_dim,
include_down_adj=self.include_down_adj,
init_method=self._init_method)
if self._max_ring_size is not None:
assert max_dim <= 2
if max_dim != self.max_dim:
self.max_dim = max_dim
makedirs(self.processed_dir)
# Now we save in opt format.
path = self.processed_paths[0]
torch.save(self.collate(complexes, self.max_dim), path)
| 4,522 | 39.747748 | 107 | py |
cwn | cwn-main/data/datasets/ring_utils.py | import numpy as np
import torch
import random
from torch_geometric.data import Data
from sklearn.preprocessing import LabelBinarizer
# TODO: Add a graph dataset for ring lookup.
def generate_ring_lookup_graph(nodes):
"""This generates a dictionary lookup ring. No longer being used for now."""
# Assign all the other nodes in the ring a unique key and value
keys = np.arange(1, nodes)
vals = np.random.permutation(nodes - 1)
oh_keys = np.array(LabelBinarizer().fit_transform(keys))
oh_vals = np.array(LabelBinarizer().fit_transform(vals))
oh_all = np.concatenate((oh_keys, oh_vals), axis=-1)
x = np.empty((nodes, oh_all.shape[1]))
x[1:, :] = oh_all
# Assign the source node one of these random keys and set the value to -1
key_idx = random.randint(0, nodes - 2)
val = vals[key_idx]
x[0, :] = 0
x[0, :oh_keys.shape[1]] = oh_keys[key_idx]
x = torch.tensor(x, dtype=torch.float32)
edge_index = []
for i in range(nodes-1):
edge_index.append([i, i + 1])
edge_index.append([i + 1, i])
# Add the edges that close the ring
edge_index.append([0, nodes - 1])
edge_index.append([nodes - 1, 0])
edge_index = np.array(edge_index, dtype=np.long).T
edge_index = torch.tensor(edge_index, dtype=torch.long)
# Create a mask for the target node of the graph
mask = torch.zeros(nodes, dtype=torch.bool)
mask[0] = 1
# Add the label of the graph as a graph label
y = torch.tensor([val], dtype=torch.long)
return Data(x=x, edge_index=edge_index, mask=mask, y=y)
def generate_ringlookup_graph_dataset(nodes, samples=10000):
# Generate the dataset
dataset = []
for i in range(samples):
graph = generate_ring_lookup_graph(nodes)
dataset.append(graph)
return dataset
def generate_ring_transfer_graph(nodes, target_label):
opposite_node = nodes // 2
# Initialise the feature matrix with a constant feature vector
# TODO: Modify the experiment to use another random constant feature per graph
x = np.ones((nodes, len(target_label)))
x[0, :] = 0.0
x[opposite_node, :] = target_label
x = torch.tensor(x, dtype=torch.float32)
edge_index = []
for i in range(nodes-1):
edge_index.append([i, i + 1])
edge_index.append([i + 1, i])
# Add the edges that close the ring
edge_index.append([0, nodes - 1])
edge_index.append([nodes - 1, 0])
edge_index = np.array(edge_index, dtype=np.long).T
edge_index = torch.tensor(edge_index, dtype=torch.long)
# Create a mask for the target node of the graph
mask = torch.zeros(nodes, dtype=torch.bool)
mask[0] = 1
# Add the label of the graph as a graph label
y = torch.tensor([np.argmax(target_label)], dtype=torch.long)
return Data(x=x, edge_index=edge_index, mask=mask, y=y)
def generate_ring_transfer_graph_dataset(nodes, classes=5, samples=10000):
# Generate the dataset
dataset = []
samples_per_class = samples // classes
for i in range(samples):
label = i // samples_per_class
target_class = np.zeros(classes)
target_class[label] = 1.0
graph = generate_ring_transfer_graph(nodes, target_class)
dataset.append(graph)
return dataset
| 3,276 | 30.509615 | 82 | py |
cwn | cwn-main/data/datasets/zinc.py | import torch
import os.path as osp
from data.utils import convert_graph_dataset_with_rings
from data.datasets import InMemoryComplexDataset
from torch_geometric.datasets import ZINC
class ZincDataset(InMemoryComplexDataset):
"""This is ZINC from the Benchmarking GNNs paper. This is a graph regression task."""
def __init__(self, root, max_ring_size, use_edge_features=False, transform=None,
pre_transform=None, pre_filter=None, subset=True,
include_down_adj=False, n_jobs=2):
self.name = 'ZINC'
self._max_ring_size = max_ring_size
self._use_edge_features = use_edge_features
self._subset = subset
self._n_jobs = n_jobs
super(ZincDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim=2, cellular=True,
include_down_adj=include_down_adj, num_classes=1)
self.data, self.slices, idx = self.load_dataset()
self.train_ids = idx[0]
self.val_ids = idx[1]
self.test_ids = idx[2]
self.num_node_type = 28
self.num_edge_type = 4
@property
def raw_file_names(self):
return ['train.pt', 'val.pt', 'test.pt']
@property
def processed_file_names(self):
name = self.name
return [f'{name}_complex.pt', f'{name}_idx.pt']
def download(self):
# Instantiating this will download and process the graph dataset.
ZINC(self.raw_dir, subset=self._subset)
def load_dataset(self):
"""Load the dataset from here and process it if it doesn't exist"""
print("Loading dataset from disk...")
data, slices = torch.load(self.processed_paths[0])
idx = torch.load(self.processed_paths[1])
return data, slices, idx
def process(self):
# At this stage, the graph dataset is already downloaded and processed
print(f"Processing cell complex dataset for {self.name}")
train_data = ZINC(self.raw_dir, subset=self._subset, split='train')
val_data = ZINC(self.raw_dir, subset=self._subset, split='val')
test_data = ZINC(self.raw_dir, subset=self._subset, split='test')
data_list = []
idx = []
start = 0
print("Converting the train dataset to a cell complex...")
train_complexes, _, _ = convert_graph_dataset_with_rings(
train_data,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_edges=self._use_edge_features,
init_rings=False,
n_jobs=self._n_jobs)
data_list += train_complexes
idx.append(list(range(start, len(data_list))))
start = len(data_list)
print("Converting the validation dataset to a cell complex...")
val_complexes, _, _ = convert_graph_dataset_with_rings(
val_data,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_edges=self._use_edge_features,
init_rings=False,
n_jobs=self._n_jobs)
data_list += val_complexes
idx.append(list(range(start, len(data_list))))
start = len(data_list)
print("Converting the test dataset to a cell complex...")
test_complexes, _, _ = convert_graph_dataset_with_rings(
test_data,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_edges=self._use_edge_features,
init_rings=False,
n_jobs=self._n_jobs)
data_list += test_complexes
idx.append(list(range(start, len(data_list))))
path = self.processed_paths[0]
print(f'Saving processed dataset in {path}....')
torch.save(self.collate(data_list, 2), path)
path = self.processed_paths[1]
print(f'Saving idx in {path}....')
torch.save(idx, path)
@property
def processed_dir(self):
"""Overwrite to change name based on edges"""
directory = super(ZincDataset, self).processed_dir
suffix0 = "_full" if self._subset is False else ""
suffix1 = f"_{self._max_ring_size}rings" if self._cellular else ""
suffix2 = "-E" if self._use_edge_features else ""
return directory + suffix0 + suffix1 + suffix2
def load_zinc_graph_dataset(root, subset=True):
raw_dir = osp.join(root, 'ZINC', 'raw')
train_data = ZINC(raw_dir, subset=subset, split='train')
val_data = ZINC(raw_dir, subset=subset, split='val')
test_data = ZINC(raw_dir, subset=subset, split='test')
data = train_data + val_data + test_data
if subset:
assert len(train_data) == 10000
assert len(val_data) == 1000
assert len(test_data) == 1000
else:
assert len(train_data) == 220011
assert len(val_data) == 24445
assert len(test_data) == 5000
idx = []
start = 0
idx.append(list(range(start, len(train_data))))
start = len(train_data)
idx.append(list(range(start, start + len(val_data))))
start = len(train_data) + len(val_data)
idx.append(list(range(start, start + len(test_data))))
return data, idx[0], idx[1], idx[2]
| 5,282 | 36.468085 | 91 | py |
cwn | cwn-main/data/datasets/dataset.py | """
The code is based on https://github.com/rusty1s/pytorch_geometric/blob/76d61eaa9fc8702aa25f29dfaa5134a169d0f1f6/torch_geometric/data/dataset.py#L19
and https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/data/in_memory_dataset.py
Copyright (c) 2020 Matthias Fey <[email protected]>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import copy
import re
from abc import ABC
import torch
import os.path as osp
from torch_geometric.data import Dataset
from itertools import repeat, product
from data.complex import Complex, Cochain
from torch import Tensor
def __repr__(obj):
if obj is None:
return 'None'
return re.sub('(<.*?)\\s.*(>)', r'\1\2', obj.__repr__())
class ComplexDataset(Dataset, ABC):
"""Base class for cochain complex datasets.
This class mirrors
https://github.com/rusty1s/pytorch_geometric/blob/76d61eaa9fc8702aa25f29dfaa5134a169d0f1f6/torch_geometric/data/dataset.py#L19
"""
def __init__(self, root=None, transform=None, pre_transform=None, pre_filter=None,
max_dim: int = None, num_classes: int = None, init_method: str = 'sum',
cellular: bool = False):
# These have to be initialised before calling the super class.
self._max_dim = max_dim
self._num_features = [None for _ in range(max_dim+1)]
self._init_method = init_method
self._cellular = cellular
super(ComplexDataset, self).__init__(root, transform, pre_transform, pre_filter)
self._num_classes = num_classes
self.train_ids = None
self.val_ids = None
self.test_ids = None
@property
def max_dim(self):
return self._max_dim
@max_dim.setter
def max_dim(self, value):
self._max_dim = value
@property
def num_classes(self):
return self._num_classes
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
prefix = "cell_" if self._cellular else ""
return osp.join(self.root, f'{prefix}complex_dim{self.max_dim}_{self._init_method}')
def num_features_in_dim(self, dim):
if dim > self.max_dim:
raise ValueError('`dim` {} larger than max allowed dimension {}.'.format(dim, self.max_dim))
if self._num_features[dim] is None:
self._look_up_num_features()
return self._num_features[dim]
def _look_up_num_features(self):
for complex in self:
for dim in range(complex.dimension + 1):
if self._num_features[dim] is None:
self._num_features[dim] = complex.cochains[dim].num_features
else:
assert self._num_features[dim] == complex.cochains[dim].num_features
def get_idx_split(self):
idx_split = {
'train': self.train_ids,
'valid': self.val_ids,
'test': self.test_ids}
return idx_split
class InMemoryComplexDataset(ComplexDataset):
"""Wrapper around ComplexDataset with functionality such as batching and storing the dataset.
This class mirrors
https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/data/in_memory_dataset.py
"""
@property
def raw_file_names(self):
r"""The name of the files to find in the :obj:`self.raw_dir` folder in
order to skip the download."""
raise NotImplementedError
@property
def processed_file_names(self):
r"""The name of the files to find in the :obj:`self.processed_dir`
folder in order to skip the processing."""
raise NotImplementedError
def download(self):
r"""Downloads the dataset to the :obj:`self.raw_dir` folder."""
raise NotImplementedError
def process(self):
r"""Processes the dataset to the :obj:`self.processed_dir` folder."""
raise NotImplementedError
def __init__(self, root=None, transform=None, pre_transform=None,
pre_filter=None, max_dim: int = None, num_classes: int = None,
include_down_adj=False, init_method=None, cellular: bool = False):
self.include_down_adj = include_down_adj
super(InMemoryComplexDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim, num_classes, init_method=init_method,
cellular=cellular)
self.data, self.slices = None, None
self.__data_list__ = None
def len(self):
for dim in range(self.max_dim + 1):
for item in self.slices[dim].values():
return len(item) - 1
return 0
def get(self, idx):
if hasattr(self, '__data_list__'):
if self.__data_list__ is None:
self.__data_list__ = self.len() * [None]
else:
data = self.__data_list__[idx]
if data is not None:
return copy.copy(data)
retrieved = [self._get_cochain(dim, idx) for dim in range(0, self.max_dim + 1)]
cochains = [r[0] for r in retrieved if not r[1]]
targets = self.data['labels']
start, end = idx, idx + 1
if torch.is_tensor(targets):
s = list(repeat(slice(None), targets.dim()))
cat_dim = 0
s[cat_dim] = slice(start, end)
else:
# TODO: come up with a better method to handle this
assert targets[start] is None
s = start
target = targets[s]
dim = self.data['dims'][idx].item()
assert dim == len(cochains) - 1
data = Complex(*cochains, y=target)
if hasattr(self, '__data_list__'):
self.__data_list__[idx] = copy.copy(data)
return data
def _get_cochain(self, dim, idx) -> (Cochain, bool):
if dim < 0 or dim > self.max_dim:
raise ValueError(f'The current dataset does not have cochains at dimension {dim}.')
cochain_data = self.data[dim]
cochain_slices = self.slices[dim]
data = Cochain(dim)
if cochain_data.__num_cells__[idx] is not None:
data.num_cells = cochain_data.__num_cells__[idx]
if cochain_data.__num_cells_up__[idx] is not None:
data.num_cells_up = cochain_data.__num_cells_up__[idx]
if cochain_data.__num_cells_down__[idx] is not None:
data.num_cells_down = cochain_data.__num_cells_down__[idx]
elif dim == 0:
data.num_cells_down = None
for key in cochain_data.keys:
item, slices = cochain_data[key], cochain_slices[key]
start, end = slices[idx].item(), slices[idx + 1].item()
data[key] = None
if start != end:
if torch.is_tensor(item):
s = list(repeat(slice(None), item.dim()))
cat_dim = cochain_data.__cat_dim__(key, item)
if cat_dim is None:
cat_dim = 0
s[cat_dim] = slice(start, end)
elif start + 1 == end:
s = slices[start]
else:
s = slice(start, end)
data[key] = item[s]
empty = (data.num_cells is None)
return data, empty
@staticmethod
def collate(data_list, max_dim):
r"""Collates a python list of data objects to the internal storage
format of :class:`InMemoryComplexDataset`."""
def init_keys(dim, keys):
cochain = Cochain(dim)
for key in keys[dim]:
cochain[key] = []
cochain.__num_cells__ = []
cochain.__num_cells_up__ = []
cochain.__num_cells_down__ = []
slc = {key: [0] for key in keys[dim]}
return cochain, slc
def collect_keys(data_list, max_dim):
keys = {dim: set() for dim in range(0, max_dim + 1)}
for complex in data_list:
for dim in keys:
if dim not in complex.cochains:
continue
cochain = complex.cochains[dim]
keys[dim] |= set(cochain.keys)
return keys
keys = collect_keys(data_list, max_dim)
types = {}
cat_dims = {}
tensor_dims = {}
data = {'labels': [], 'dims': []}
slices = {}
for dim in range(0, max_dim + 1):
data[dim], slices[dim] = init_keys(dim, keys)
for complex in data_list:
# Collect cochain-wise items
for dim in range(0, max_dim + 1):
# Get cochain, if present
cochain = None
if dim in complex.cochains:
cochain = complex.cochains[dim]
# Iterate on keys
for key in keys[dim]:
if cochain is not None and hasattr(cochain, key) and cochain[key] is not None:
data[dim][key].append(cochain[key])
if isinstance(cochain[key], Tensor) and cochain[key].dim() > 0:
cat_dim = cochain.__cat_dim__(key, cochain[key])
cat_dim = 0 if cat_dim is None else cat_dim
s = slices[dim][key][-1] + cochain[key].size(cat_dim)
if key not in cat_dims:
cat_dims[key] = cat_dim
else:
assert cat_dim == cat_dims[key]
if key not in tensor_dims:
tensor_dims[key] = cochain[key].dim()
else:
assert cochain[key].dim() == tensor_dims[key]
else:
s = slices[dim][key][-1] + 1
if key not in types:
types[key] = type(cochain[key])
else:
assert type(cochain[key]) is types[key]
else:
s = slices[dim][key][-1] + 0
slices[dim][key].append(s)
# Handle non-keys
# TODO: could they be considered as keys as well?
num = None
num_up = None
num_down = None
if cochain is not None:
if hasattr(cochain, '__num_cells__'):
num = cochain.__num_cells__
if hasattr(cochain, '__num_cells_up__'):
num_up = cochain.__num_cells_up__
if hasattr(cochain, '__num_cells_down__'):
num_down = cochain.__num_cells_down__
data[dim].__num_cells__.append(num)
data[dim].__num_cells_up__.append(num_up)
data[dim].__num_cells_down__.append(num_down)
# Collect complex-wise label(s) and dims
if not hasattr(complex, 'y'):
complex.y = None
if isinstance(complex.y, Tensor):
assert complex.y.size(0) == 1
data['labels'].append(complex.y)
data['dims'].append(complex.dimension)
# Pack lists into tensors
# Cochains
for dim in range(0, max_dim + 1):
for key in keys[dim]:
if types[key] is Tensor and len(data_list) > 1:
if tensor_dims[key] > 0:
cat_dim = cat_dims[key]
data[dim][key] = torch.cat(data[dim][key], dim=cat_dim)
else:
data[dim][key] = torch.stack(data[dim][key])
elif types[key] is Tensor: # Don't duplicate attributes...
data[dim][key] = data[dim][key][0]
elif types[key] is int or types[key] is float:
data[dim][key] = torch.tensor(data[dim][key])
slices[dim][key] = torch.tensor(slices[dim][key], dtype=torch.long)
# Labels and dims
item = data['labels'][0]
if isinstance(item, Tensor) and len(data_list) > 1:
if item.dim() > 0:
cat_dim = 0
data['labels'] = torch.cat(data['labels'], dim=cat_dim)
else:
data['labels'] = torch.stack(data['labels'])
elif isinstance(item, Tensor):
data['labels'] = data['labels'][0]
elif isinstance(item, int) or isinstance(item, float):
data['labels'] = torch.tensor(data['labels'])
data['dims'] = torch.tensor(data['dims'])
return data, slices
def copy(self, idx=None):
if idx is None:
data_list = [self.get(i) for i in range(len(self))]
else:
data_list = [self.get(i) for i in idx]
dataset = copy.copy(self)
dataset.__indices__ = None
dataset.__data_list__ = data_list
dataset.data, dataset.slices = self.collate(data_list)
return dataset
def get_split(self, split):
if split not in ['train', 'valid', 'test']:
raise ValueError(f'Unknown split {split}.')
idx = self.get_idx_split()[split]
if idx is None:
raise AssertionError("No split information found.")
if self.__indices__ is not None:
raise AssertionError("Cannot get the split for a subset of the original dataset.")
return self[idx]
| 14,872 | 38.873995 | 147 | py |
cwn | cwn-main/data/datasets/test_zinc.py | import torch
import os.path as osp
import pytest
from data.data_loading import load_dataset
from data.helper_test import (check_edge_index_are_the_same,
check_edge_attr_are_the_same, get_rings,
get_complex_rings)
from torch_geometric.datasets import ZINC
@pytest.mark.slow
def test_zinc_splits_are_retained():
dataset1 = load_dataset("ZINC", max_ring_size=7, use_edge_features=True)
dataset1_train = dataset1.get_split('train')
dataset1_valid = dataset1.get_split('valid')
dataset1_test = dataset1.get_split('test')
raw_dir = osp.join(dataset1.root, 'raw')
dataset2_train = ZINC(raw_dir, subset=True, split='train')
dataset2_valid = ZINC(raw_dir, subset=True, split='val')
dataset2_test = ZINC(raw_dir, subset=True, split='test')
datasets1 = [dataset1_train, dataset1_valid, dataset1_test]
datasets2 = [dataset2_train, dataset2_valid, dataset2_test]
datasets = zip(datasets1, datasets2)
for datas1, datas2 in datasets:
for i, _ in enumerate(datas1):
data1, data2 = datas1[i], datas2[i]
assert torch.equal(data1.y, data2.y)
assert torch.equal(data1.cochains[0].x, data2.x)
assert data1.cochains[1].x.size(0) == (data2.edge_index.size(1) // 2)
check_edge_index_are_the_same(data1.cochains[0].upper_index, data2.edge_index)
check_edge_attr_are_the_same(data1.cochains[1].boundary_index,
data1.cochains[1].x, data2.edge_index, data2.edge_attr)
@pytest.mark.slow
def test_we_find_only_the_induced_cycles_on_zinc():
max_ring = 7
dataset = load_dataset("ZINC", max_ring_size=max_ring, use_edge_features=True)
# Check only on validation to save time. I've also run once on the whole dataset and passes.
dataset = dataset.get_split('valid')
for complex in dataset:
nx_rings = get_rings(complex.nodes.num_cells, complex.nodes.upper_index,
max_ring=max_ring)
if 2 not in complex.cochains:
assert len(nx_rings) == 0
continue
complex_rings = get_complex_rings(complex.cochains[2].boundary_index, complex.edges.boundary_index)
assert len(complex_rings) > 0
assert len(nx_rings) == complex.cochains[2].num_cells
assert nx_rings == complex_rings
| 2,395 | 38.933333 | 107 | py |
cwn | cwn-main/data/datasets/ocean_utils.py | """
Based on
- https://github.com/nglaze00/SCoNe_GCN/blob/master/ocean_drifters_data/buoy_data.py
- https://github.com/nglaze00/SCoNe_GCN/blob/master/trajectory_analysis/synthetic_data_gen.py
MIT License
Copyright (c) 2021 Nicholas Glaze
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import networkx as nx
import numpy as np
import h5py
import os.path as osp
import matplotlib.pyplot as plt
import data.datasets.flow_utils as fu
from definitions import ROOT_DIR
from tqdm import tqdm
def faces_from_B2(B2, E):
"""
Given a B2 matrix, returns the list of faces.
"""
faces_B2 = []
for j in range(B2.shape[1]):
edge_idxs = np.where(B2[:, j] != 0)
edges = E[edge_idxs]
nodes = set()
for e in edges:
for n in e:
nodes.add(n)
faces_B2.append(tuple(sorted(nodes)))
return faces_B2
def path_to_flow(path, edge_to_idx, m):
'''Instantiates a 1-cochain from a path, accounting for the edge orientation.
path: list of nodes
E_lookup: dictionary mapping edge tuples to indices
m: number of edges
'''
l = len(path)
f = np.zeros([m,1])
for j in range(l-1):
v0 = path[j]
v1 = path[j+1]
if v0 < v1:
k = edge_to_idx[(v0,v1)]
f[k] += 1
else:
k = edge_to_idx[(v1,v0)]
f[k] -= 1
return f
def incidence_matrices(G, V, E, faces, edge_to_idx):
"""
Returns incidence matrices B1 and B2
:param G: NetworkX DiGraph
:param V: list of nodes
:param E: list of edges
:param faces: list of faces in G
Returns B1 (|V| x |E|) and B2 (|E| x |faces|)
B1[i][j]: -1 if node i is tail of edge j, 1 if node i is head of edge j, else 0 (tail -> head) (smaller -> larger)
B2[i][j]: 1 if edge i appears sorted in face j, -1 if edge i appears reversed in face j, else 0; given faces with sorted node order
"""
B1 = np.array(nx.incidence_matrix(G, nodelist=V, edgelist=E, oriented=True).todense())
B2 = np.zeros([len(E),len(faces)])
for f_idx, face in enumerate(faces): # face is sorted
edges = [face[:-1], face[1:], [face[0], face[2]]]
e_idxs = [edge_to_idx[tuple(e)] for e in edges]
B2[e_idxs[:-1], f_idx] = 1
B2[e_idxs[-1], f_idx] = -1
return B1, B2
def strip_paths(paths):
"""
Remove edges which are sequentially repeated in a path, e.g. [a, b, c, d, c, d, e, f] -> [a, b, c, d, e, f]
"""
res_all = []
for path in paths:
res = []
for node in path:
if len(res) < 2:
res.append(node)
continue
if node == res[-2]:
res.pop()
continue
else:
res.append(node)
res_all.append(res)
return res_all
def color_faces(G, V, coords, faces, filename='graph_faces.pdf', paths=None):
"""
Saves a plot of the graph, with faces colored in
"""
plt.figure()
for f in np.array(faces):
plt.gca().add_patch(plt.Polygon(coords[f], facecolor=(173/256,216/256,240/256, 0.4), ec='k', linewidth=0.3))
nx.draw_networkx(G, with_labels=False,
width=0.3,
node_size=0, pos=dict(zip(V, coords)))
if paths:
coords_dict = {i: xy for i, xy in enumerate(coords)}
for path in paths:
edges = [(path[i], path[i+1]) for i in range(len(path) - 1)]
nx.draw_networkx_edges(G.to_directed(), pos=coords_dict, edgelist=edges, edge_color='black', width=1.5,
arrows=True, arrowsize=7, node_size=3)
plt.scatter(x=[np.mean(coords[:, 0]) - 0.03], y=[np.mean(coords[:, 1])])
plt.savefig(filename)
def orientation(p1, p2, p3):
# to find the orientation of
# an ordered triplet (p1,p2,p3)
# function returns the following values:
# 0 : Colinear points
# 1 : Clockwise points
# 2 : Counterclockwise
val = (float(p2[1] - p1[1]) * (p3[0] - p2[0])) - (float(p2[0] - p1[0]) * (p3[1] - p2[1]))
if val > 0:
# Clockwise orientation
return 0
elif val < 0:
# Counterclockwise orientation
return 1
else:
print(p1, p2, p3)
raise ValueError('Points should not be collinear')
def extract_label(path, coords):
# This is the center of madagascar. We will use it to compute the clockwise orientation
# of the flow.
center = [np.mean(coords[:, 0]) - 0.03, np.mean(coords[:, 1])]
return orientation(center, coords[path[0]], coords[path[-1]])
def load_ocean_dataset(train_orient='default', test_orient='default'):
raw_dir = osp.join(ROOT_DIR, 'datasets', 'OCEAN', 'raw')
raw_filename = osp.join(raw_dir, 'dataBuoys.jld2')
f = h5py.File(raw_filename, 'r')
# elist (edge list)
edge_list = f['elist'][:] - 1 # 1-index -> 0-index
# tlist (triangle list)
face_list = f['tlist'][:] - 1
# print("Faces", np.shape(face_list))
# NodeToHex (map node id <-> hex coords) # nodes are 1-indexed in data source
node_hex_map = [tuple(f[x][()]) for x in f['NodeToHex'][:]]
hex_node_map = {tuple(hex_coords): node for node, hex_coords in enumerate(node_hex_map)}
# coords
hex_coords = np.array([tuple(x) for x in f['HexcentersXY'][()]])
# nodes
traj_nodes = [[f[x][()] - 1 for x in f[ref][()]] for ref in f['TrajectoriesNodes'][:]]
# generate graph + faces
G = nx.Graph()
G.add_edges_from([(edge_list[0][i], edge_list[1][i]) for i in range(len(edge_list[0]))])
V, E = np.array(sorted(G.nodes)), np.array([sorted(x) for x in sorted(G.edges)])
faces = np.array(sorted([[face_list[j][i] for j in range(3)] for i in range(len(face_list[0]))]))
edge_to_idx = {tuple(e): i for i, e in enumerate(E)}
coords = hex_coords
valid_idxs = np.arange(len(coords))
# B1, B2
B1, B2 = incidence_matrices(G, V, E, faces, edge_to_idx)
# Trajectories
G_undir = G.to_undirected()
stripped_paths = strip_paths(traj_nodes)
paths = [path for path in stripped_paths if len(path) >= 5]
new_paths = []
for path in paths:
new_path = path if path[-1] != path[0] else path[:-1]
new_paths.append(new_path)
paths = new_paths
print("Max length path", max([len(path) for path in paths]))
# Print graph info
print(np.mean([len(G[i]) for i in V]))
print('# nodes: {}, # edges: {}, # faces: {}'.format(*B1.shape, B2.shape[1]))
print('# paths: {}, # paths with prefix length >= 3: {}'.format(len(traj_nodes), len(paths)))
# Save graph image to file
# filename = osp.join(raw_dir, 'madagascar_graph_faces_paths.pdf')
# color_faces(G, V, coords, faces_from_B2(B2, E), filename=filename, paths=[paths[100]])
# train / test masks
np.random.seed(1)
train_mask = np.asarray([1] * round(len(paths) * 0.8) + [0] * round(len(paths) * 0.2))
np.random.shuffle(train_mask)
test_mask = 1 - train_mask
flows = np.array([path_to_flow(p, edge_to_idx, len(E)) for p in paths])
labels = np.array([extract_label(p, coords) for p in paths], dtype=int)
print("Label 14", labels[100])
# avg_clock = np.array([coords[i] for i, _ in enumerate(paths) if labels[i] == 0])
# print("Average clockwise position", np.mean(avg_clock[:, 0]), np.mean(avg_clock[:, 1]))
print('Flows', np.shape(flows))
print('Train samples:', sum(train_mask))
print('Test samples:', sum(test_mask))
assert len(labels) == len(train_mask)
print('Train Clockwise', sum(1 - labels[train_mask.astype(bool)]))
print('Train Anticlockwise', sum(labels[train_mask.astype(bool)]))
print('Test Clockwise', sum(1 - labels[test_mask.astype(bool)]))
print('Test Anticlockwise', sum(labels[test_mask.astype(bool)]))
assert B1.shape[1] == B2.shape[0]
num_edges = B1.shape[1]
train_cochains, test_cochains = [], []
for i in tqdm(range(len(flows)), desc='Processing dataset'):
if train_mask[i] == 1:
T2 = fu.get_orient_matrix(num_edges, train_orient)
cochain = fu.build_cochain(B1, B2, T2, flows[i], labels[i], G_undir)
train_cochains.append(cochain)
else:
T2 = fu.get_orient_matrix(num_edges, test_orient)
cochain = fu.build_cochain(B1, B2, T2, flows[i], labels[i], G_undir)
test_cochains.append(cochain)
return train_cochains, test_cochains, G_undir
| 9,466 | 34.193309 | 135 | py |
cwn | cwn-main/data/datasets/tu.py | import os
import torch
import pickle
import numpy as np
from definitions import ROOT_DIR
from data.tu_utils import load_data, S2V_to_PyG, get_fold_indices
from data.utils import convert_graph_dataset_with_gudhi, convert_graph_dataset_with_rings
from data.datasets import InMemoryComplexDataset
def load_tu_graph_dataset(name, root=os.path.join(ROOT_DIR, 'datasets'), degree_as_tag=False, fold=0, seed=0):
raw_dir = os.path.join(root, name, 'raw')
load_from = os.path.join(raw_dir, '{}_graph_list_degree_as_tag_{}.pkl'.format(name, degree_as_tag))
if os.path.isfile(load_from):
with open(load_from, 'rb') as handle:
graph_list = pickle.load(handle)
else:
data, num_classes = load_data(raw_dir, name, degree_as_tag)
print('Converting graph data into PyG format...')
graph_list = [S2V_to_PyG(datum) for datum in data]
with open(load_from, 'wb') as handle:
pickle.dump(graph_list, handle)
train_filename = os.path.join(raw_dir, '10fold_idx', 'train_idx-{}.txt'.format(fold + 1))
test_filename = os.path.join(raw_dir, '10fold_idx', 'test_idx-{}.txt'.format(fold + 1))
if os.path.isfile(train_filename) and os.path.isfile(test_filename):
# NB: we consider the loaded test indices as val_ids ones and set test_ids to None
# to make it more convenient to work with the training pipeline
train_ids = np.loadtxt(train_filename, dtype=int).tolist()
val_ids = np.loadtxt(test_filename, dtype=int).tolist()
else:
train_ids, val_ids = get_fold_indices(graph_list, seed, fold)
test_ids = None
return graph_list, train_ids, val_ids, test_ids
class TUDataset(InMemoryComplexDataset):
"""A dataset of complexes obtained by lifting graphs from TUDatasets."""
def __init__(self, root, name, max_dim=2, num_classes=2, degree_as_tag=False, fold=0,
init_method='sum', seed=0, include_down_adj=False, max_ring_size=None):
self.name = name
self.degree_as_tag = degree_as_tag
assert max_ring_size is None or max_ring_size > 3
self._max_ring_size = max_ring_size
cellular = (max_ring_size is not None)
if cellular:
assert max_dim == 2
super(TUDataset, self).__init__(root, max_dim=max_dim, num_classes=num_classes,
init_method=init_method, include_down_adj=include_down_adj, cellular=cellular)
self.data, self.slices = torch.load(self.processed_paths[0])
self.fold = fold
self.seed = seed
train_filename = os.path.join(self.raw_dir, '10fold_idx', 'train_idx-{}.txt'.format(fold + 1))
test_filename = os.path.join(self.raw_dir, '10fold_idx', 'test_idx-{}.txt'.format(fold + 1))
if os.path.isfile(train_filename) and os.path.isfile(test_filename):
# NB: we consider the loaded test indices as val_ids ones and set test_ids to None
# to make it more convenient to work with the training pipeline
self.train_ids = np.loadtxt(train_filename, dtype=int).tolist()
self.val_ids = np.loadtxt(test_filename, dtype=int).tolist()
else:
train_ids, val_ids = get_fold_indices(self, self.seed, self.fold)
self.train_ids = train_ids
self.val_ids = val_ids
self.test_ids = None
# TODO: Add this later to our zip
# tune_train_filename = os.path.join(self.raw_dir, 'tests_train_split.txt'.format(fold + 1))
# self.tune_train_ids = np.loadtxt(tune_train_filename, dtype=int).tolist()
# tune_test_filename = os.path.join(self.raw_dir, 'tests_val_split.txt'.format(fold + 1))
# self.tune_val_ids = np.loadtxt(tune_test_filename, dtype=int).tolist()
# self.tune_test_ids = None
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
directory = super(TUDataset, self).processed_dir
suffix = f"_{self._max_ring_size}rings" if self._cellular else ""
suffix += f"_down_adj" if self.include_down_adj else ""
return directory + suffix
@property
def processed_file_names(self):
return ['{}_complex_list.pt'.format(self.name)]
@property
def raw_file_names(self):
# The processed graph files are our raw files.
# They are obtained when running the initial data conversion S2V_to_PyG.
return ['{}_graph_list_degree_as_tag_{}.pkl'.format(self.name, self.degree_as_tag)]
def download(self):
# This will process the raw data into a list of PyG Data objs.
data, num_classes = load_data(self.raw_dir, self.name, self.degree_as_tag)
self._num_classes = num_classes
print('Converting graph data into PyG format...')
graph_list = [S2V_to_PyG(datum) for datum in data]
with open(self.raw_paths[0], 'wb') as handle:
pickle.dump(graph_list, handle)
def process(self):
with open(self.raw_paths[0], 'rb') as handle:
graph_list = pickle.load(handle)
if self._cellular:
print("Converting the dataset accounting for rings...")
complexes, _, _ = convert_graph_dataset_with_rings(graph_list, max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_method=self._init_method,
init_edges=True, init_rings=True)
else:
print("Converting the dataset with gudhi...")
# TODO: eventually remove the following comment
# What about the init_method here? Adding now, although I remember we had handled this
complexes, _, _ = convert_graph_dataset_with_gudhi(graph_list, expansion_dim=self.max_dim,
include_down_adj=self.include_down_adj,
init_method=self._init_method)
torch.save(self.collate(complexes, self.max_dim), self.processed_paths[0])
def get_tune_idx_split(self):
raise NotImplementedError('Not implemented yet')
# idx_split = {
# 'train': self.tune_train_ids,
# 'valid': self.tune_val_ids,
# 'test': self.tune_test_ids}
# return idx_split
| 6,539 | 49.307692 | 110 | py |
cwn | cwn-main/data/datasets/plot_flow_dataset.py | import seaborn as sns
import matplotlib.pyplot as plt
import os
from data.datasets import FlowDataset
from definitions import ROOT_DIR
sns.set_style('white')
sns.color_palette("tab10")
def plot_arrow(p1, p2, color='red'):
plt.arrow(p1[0], p1[1], p2[0] - p1[0], p2[1] - p1[1], color=color,
shape='full', lw=3, length_includes_head=True, head_width=.01, zorder=10)
def visualise_flow_dataset():
root = os.path.join(ROOT_DIR, 'datasets')
name = 'FLOW'
dataset = FlowDataset(os.path.join(root, name), name, num_points=1000, train_samples=1000,
val_samples=200, classes=3, load_graph=True)
G = dataset.G
edge_to_tuple = G.graph['edge_to_tuple']
triangles = G.graph['triangles']
points = G.graph['points']
plt.figure(figsize=(10, 8))
plt.triplot(points[:, 0], points[:, 1], triangles)
plt.plot(points[:, 0], points[:, 1], 'o')
for i, cochain in enumerate([dataset[180], dataset[480]]):
colors = ['red', 'navy', 'purple']
color = colors[i]
x = cochain.x
#
# source_edge = 92
# source_points = edge_to_tuple[source_edge]
# plot_arrow(points[source_points[0]], points[source_points[1]], color='black')
path_length = 0
for i in range(len(x)):
flow = x[i].item()
if flow == 0:
continue
path_length += 1
nodes1 = edge_to_tuple[i]
if flow > 0:
p1, p2 = points[nodes1[0]], points[nodes1[1]]
else:
p1, p2 = points[nodes1[1]], points[nodes1[0]],
plt.arrow(p1[0], p1[1], p2[0] - p1[0], p2[1] - p1[1], color=color,
shape='full', lw=3, length_includes_head=True, head_width=.01, zorder=10)
# lower_index = cochain.lower_index
# for i in range(lower_index.size(1)):
# n1, n2 = lower_index[0, i].item(), lower_index[1, i].item()
# if n1 == source_edge:
# source_points = edge_to_tuple[n2]
# orient = cochain.lower_orient[i].item()
# color = 'green' if orient == 1.0 else 'yellow'
# plot_arrow(points[source_points[0]], points[source_points[1]], color=color)
# upper_index = cochain.upper_index
# for i in range(upper_index.size(1)):
# n1, n2 = upper_index[0, i].item(), upper_index[1, i].item()
# if n1 == source_edge:
# source_points = edge_to_tuple[n2]
# orient = cochain.upper_orient[i].item()
# color = 'green' if orient == 1.0 else 'yellow'
# plot_arrow(points[source_points[0]], points[source_points[1]], color=color)
plt.show()
if __name__ == "__main__":
visualise_flow_dataset()
| 2,723 | 33.05 | 94 | py |
cwn | cwn-main/data/datasets/ogb.py | import torch
import os.path as osp
from data.utils import convert_graph_dataset_with_rings
from data.datasets import InMemoryComplexDataset
from ogb.graphproppred import PygGraphPropPredDataset
class OGBDataset(InMemoryComplexDataset):
"""This is OGB graph-property prediction. This are graph-wise classification tasks."""
def __init__(self, root, name, max_ring_size, use_edge_features=False, transform=None,
pre_transform=None, pre_filter=None, init_method='sum',
include_down_adj=False, simple=False, n_jobs=2):
self.name = name
self._max_ring_size = max_ring_size
self._use_edge_features = use_edge_features
self._simple = simple
self._n_jobs = n_jobs
super(OGBDataset, self).__init__(root, transform, pre_transform, pre_filter,
max_dim=2, init_method=init_method,
include_down_adj=include_down_adj, cellular=True)
self.data, self.slices, idx, self.num_tasks = self.load_dataset()
self.train_ids = idx['train']
self.val_ids = idx['valid']
self.test_ids = idx['test']
@property
def raw_file_names(self):
name = self.name.replace('-', '_') # Replacing is to follow OGB folder naming convention
# The processed graph files are our raw files.
return [f'{name}/processed/geometric_data_processed.pt']
@property
def processed_file_names(self):
return [f'{self.name}_complex.pt', f'{self.name}_idx.pt', f'{self.name}_tasks.pt']
@property
def processed_dir(self):
"""Overwrite to change name based on edge and simple feats"""
directory = super(OGBDataset, self).processed_dir
suffix1 = f"_{self._max_ring_size}rings" if self._cellular else ""
suffix2 = "-E" if self._use_edge_features else ""
suffix3 = "-S" if self._simple else ""
return directory + suffix1 + suffix2 + suffix3
def download(self):
# Instantiating this will download and process the graph dataset.
dataset = PygGraphPropPredDataset(self.name, self.raw_dir)
def load_dataset(self):
"""Load the dataset from here and process it if it doesn't exist"""
print("Loading dataset from disk...")
data, slices = torch.load(self.processed_paths[0])
idx = torch.load(self.processed_paths[1])
tasks = torch.load(self.processed_paths[2])
return data, slices, idx, tasks
def process(self):
# At this stage, the graph dataset is already downloaded and processed
dataset = PygGraphPropPredDataset(self.name, self.raw_dir)
split_idx = dataset.get_idx_split()
if self._simple: # Only retain the top two node/edge features
print('Using simple features')
dataset.data.x = dataset.data.x[:,:2]
dataset.data.edge_attr = dataset.data.edge_attr[:,:2]
# NB: the init method would basically have no effect if
# we use edge features and do not initialize rings.
print(f"Converting the {self.name} dataset to a cell complex...")
complexes, _, _ = convert_graph_dataset_with_rings(
dataset,
max_ring_size=self._max_ring_size,
include_down_adj=self.include_down_adj,
init_method=self._init_method,
init_edges=self._use_edge_features,
init_rings=False,
n_jobs=self._n_jobs)
print(f'Saving processed dataset in {self.processed_paths[0]}...')
torch.save(self.collate(complexes, self.max_dim), self.processed_paths[0])
print(f'Saving idx in {self.processed_paths[1]}...')
torch.save(split_idx, self.processed_paths[1])
print(f'Saving num_tasks in {self.processed_paths[2]}...')
torch.save(dataset.num_tasks, self.processed_paths[2])
def load_ogb_graph_dataset(root, name):
raw_dir = osp.join(root, 'raw')
dataset = PygGraphPropPredDataset(name, raw_dir)
idx = dataset.get_idx_split()
return dataset, idx['train'], idx['valid'], idx['test']
| 4,176 | 42.061856 | 97 | py |
cwn | cwn-main/data/datasets/ringlookup.py | import torch
import os.path as osp
from data.datasets import InMemoryComplexDataset
from data.datasets.ring_utils import generate_ringlookup_graph_dataset
from data.utils import convert_graph_dataset_with_rings
class RingLookupDataset(InMemoryComplexDataset):
"""A dataset where the task is to perform dictionary lookup on the features
of a set of nodes forming a ring. The feature of each node is composed of a key and a value
and one must assign to a target node the value of the key its feature encodes.
"""
def __init__(self, root, nodes=10):
self.name = 'RING-LOOKUP'
self._nodes = nodes
super(RingLookupDataset, self).__init__(
root, None, None, None, max_dim=2, cellular=True, num_classes=nodes-1)
self.data, self.slices = torch.load(self.processed_paths[0])
idx = torch.load(self.processed_paths[1])
self.train_ids = idx[0]
self.val_ids = idx[1]
self.test_ids = idx[2]
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
return osp.join(self.root, 'complex')
@property
def processed_file_names(self):
return [f'ringlookup-n{self._nodes}.pkl', f'idx-n{self._nodes}.pkl']
@property
def raw_file_names(self):
# No raw files, but must be implemented
return []
def download(self):
# Nothing to download, but must be implemented
pass
def process(self):
train = generate_ringlookup_graph_dataset(self._nodes, samples=10000)
val = generate_ringlookup_graph_dataset(self._nodes, samples=1000)
dataset = train + val
train_ids = list(range(len(train)))
val_ids = list(range(len(train), len(train) + len(val)))
print("Converting dataset to a cell complex...")
complexes, _, _ = convert_graph_dataset_with_rings(
dataset,
max_ring_size=self._nodes,
include_down_adj=False,
init_edges=True,
init_rings=True,
n_jobs=4)
for complex in complexes:
# Add mask for the target node.
mask = torch.zeros(complex.nodes.num_cells, dtype=torch.bool)
mask[0] = 1
setattr(complex.cochains[0], 'mask', mask)
# Make HOF zero
complex.edges.x = torch.zeros_like(complex.edges.x)
complex.two_cells.x = torch.zeros_like(complex.two_cells.x)
assert complex.two_cells.num_cells == 1
path = self.processed_paths[0]
print(f'Saving processed dataset in {path}....')
torch.save(self.collate(complexes, 2), path)
idx = [train_ids, val_ids, None]
path = self.processed_paths[1]
print(f'Saving idx in {path}....')
torch.save(idx, path)
def load_ring_lookup_dataset(nodes=10):
train = generate_ringlookup_graph_dataset(nodes, samples=10000)
val = generate_ringlookup_graph_dataset(nodes, samples=1000)
dataset = train + val
train_ids = list(range(len(train)))
val_ids = list(range(len(train), len(train) + len(val)))
return dataset, train_ids, val_ids, None
| 3,214 | 32.842105 | 98 | py |
cwn | cwn-main/data/datasets/test_ocean.py | import torch
import pytest
from data.datasets.ocean_utils import load_ocean_dataset
@pytest.mark.data
def test_ocean_dataset_generation():
train, test, _ = load_ocean_dataset()
assert len(train) == 160
assert len(test) == 40
for cochain in train + test:
# checks the upper/lower orientation features are consistent
# in shape with the upper/lower indices
assert len(cochain.upper_orient) == cochain.upper_index.size(1)
assert len(cochain.lower_orient) == cochain.lower_index.size(1)
# checks the upper and lower indices are consistent with the number of edges
assert cochain.upper_index.max() < cochain.x.size(0), print(cochain.upper_index.max(),
cochain.x.size(0))
assert cochain.lower_index.max() < cochain.x.size(0), print(cochain.lower_index.max(),
cochain.x.size(0))
# checks the values for orientations are either +1 (coherent) or -1 (not coherent)
assert (torch.sum(cochain.upper_orient == 1)
+ torch.sum(cochain.upper_orient == -1) == cochain.upper_orient.numel())
assert (torch.sum(cochain.lower_orient == 1)
+ torch.sum(cochain.lower_orient == -1) == cochain.lower_orient.numel())
| 1,247 | 43.571429 | 94 | py |
cwn | cwn-main/data/datasets/ringtransfer.py | import torch
import os.path as osp
from data.datasets import InMemoryComplexDataset
from data.datasets.ring_utils import generate_ring_transfer_graph_dataset
from data.utils import convert_graph_dataset_with_rings
class RingTransferDataset(InMemoryComplexDataset):
"""A dataset where the task is to transfer features from a source node to a target node
placed on the other side of a ring.
"""
def __init__(self, root, nodes=10, train=5000, test=500):
self.name = 'RING-TRANSFER'
self._nodes = nodes
self._num_classes = 5
self._train = train
self._test = test
super(RingTransferDataset, self).__init__(root, None, None, None,
max_dim=2, cellular=True, num_classes=self._num_classes)
self.data, self.slices = torch.load(self.processed_paths[0])
idx = torch.load(self.processed_paths[1])
self.train_ids = idx[0]
self.val_ids = idx[1]
self.test_ids = idx[2]
@property
def processed_dir(self):
"""This is overwritten, so the cellular complex data is placed in another folder"""
return osp.join(self.root, 'complex')
@property
def processed_file_names(self):
return [f'ringtree-n{self._nodes}.pkl', f'idx-n{self._nodes}.pkl']
@property
def raw_file_names(self):
# No raw files, but must be implemented
return []
def download(self):
# Nothing to download, but must be implemented
pass
def process(self):
train = generate_ring_transfer_graph_dataset(self._nodes, classes=self._num_classes,
samples=self._train)
val = generate_ring_transfer_graph_dataset(self._nodes, classes=self._num_classes,
samples=self._test)
dataset = train + val
train_ids = list(range(len(train)))
val_ids = list(range(len(train), len(train) + len(val)))
print("Converting dataset to a cell complex...")
complexes, _, _ = convert_graph_dataset_with_rings(
dataset,
max_ring_size=self._nodes,
include_down_adj=False,
init_edges=True,
init_rings=True,
n_jobs=4)
for complex in complexes:
# Add mask for the target node.
mask = torch.zeros(complex.nodes.num_cells, dtype=torch.bool)
mask[0] = 1
setattr(complex.cochains[0], 'mask', mask)
# Make HOF zero
complex.edges.x = torch.zeros_like(complex.edges.x)
complex.two_cells.x = torch.zeros_like(complex.two_cells.x)
path = self.processed_paths[0]
print(f'Saving processed dataset in {path}....')
torch.save(self.collate(complexes, 2), path)
idx = [train_ids, val_ids, None]
path = self.processed_paths[1]
print(f'Saving idx in {path}....')
torch.save(idx, path)
def load_ring_transfer_dataset(nodes=10, train=5000, test=500, classes=5):
train = generate_ring_transfer_graph_dataset(nodes, classes=classes, samples=train)
val = generate_ring_transfer_graph_dataset(nodes, classes=classes, samples=test)
dataset = train + val
train_ids = list(range(len(train)))
val_ids = list(range(len(train), len(train) + len(val)))
return dataset, train_ids, val_ids, None
| 3,322 | 32.908163 | 92 | py |
cwn | cwn-main/data/datasets/__init__.py | from data.datasets.dataset import ComplexDataset, InMemoryComplexDataset
from data.datasets.sr import SRDataset, load_sr_graph_dataset
from data.datasets.cluster import ClusterDataset
from data.datasets.tu import TUDataset, load_tu_graph_dataset
from data.datasets.flow import FlowDataset
from data.datasets.ocean import OceanDataset
from data.datasets.zinc import ZincDataset, load_zinc_graph_dataset
from data.datasets.dummy import DummyDataset, DummyMolecularDataset
from data.datasets.csl import CSLDataset
from data.datasets.ogb import OGBDataset, load_ogb_graph_dataset
from data.datasets.peptides_functional import PeptidesFunctionalDataset, load_pep_f_graph_dataset
from data.datasets.peptides_structural import PeptidesStructuralDataset, load_pep_s_graph_dataset
from data.datasets.ringtransfer import RingTransferDataset, load_ring_transfer_dataset
from data.datasets.ringlookup import RingLookupDataset, load_ring_lookup_dataset
| 941 | 57.875 | 97 | py |
cwn | cwn-main/data/datasets/dummy.py | import torch
from data.datasets import InMemoryComplexDataset
from data.dummy_complexes import get_testing_complex_list, get_mol_testing_complex_list
class DummyDataset(InMemoryComplexDataset):
"""A dummy dataset using a list of hand-crafted cell complexes with many edge cases."""
def __init__(self, root):
self.name = 'DUMMY'
super(DummyDataset, self).__init__(root, max_dim=3, num_classes=2,
init_method=None, include_down_adj=True, cellular=False)
self.data, self.slices = torch.load(self.processed_paths[0])
self.train_ids = list(range(self.len()))
self.val_ids = list(range(self.len()))
self.test_ids = list(range(self.len()))
@property
def processed_file_names(self):
name = self.name
return [f'{name}_complex_list.pt']
@property
def raw_file_names(self):
# The processed graph files are our raw files.
# They are obtained when running the initial data conversion S2V_to_PyG.
return []
def download(self):
return
@staticmethod
def factory():
complexes = get_testing_complex_list()
for c, complex in enumerate(complexes):
complex.y = torch.LongTensor([c % 2])
return complexes
def process(self):
print("Instantiating complexes...")
complexes = self.factory()
torch.save(self.collate(complexes, self.max_dim), self.processed_paths[0])
class DummyMolecularDataset(InMemoryComplexDataset):
"""A dummy dataset using a list of hand-crafted molecular cell complexes with many edge cases."""
def __init__(self, root, remove_2feats=False):
self.name = 'DUMMYM'
self.remove_2feats = remove_2feats
super(DummyMolecularDataset, self).__init__(root, max_dim=2, num_classes=2,
init_method=None, include_down_adj=True, cellular=True)
self.data, self.slices = torch.load(self.processed_paths[0])
self.train_ids = list(range(self.len()))
self.val_ids = list(range(self.len()))
self.test_ids = list(range(self.len()))
@property
def processed_file_names(self):
name = self.name
remove_2feats = self.remove_2feats
fn = f'{name}_complex_list'
if remove_2feats:
fn += '_removed_2feats'
fn += '.pt'
return [fn]
@property
def raw_file_names(self):
# The processed graph files are our raw files.
# They are obtained when running the initial data conversion S2V_to_PyG.
return []
def download(self):
return
@staticmethod
def factory(remove_2feats=False):
complexes = get_mol_testing_complex_list()
for c, complex in enumerate(complexes):
if remove_2feats:
if 2 in complex.cochains:
complex.cochains[2].x = None
complex.y = torch.LongTensor([c % 2])
return complexes
def process(self):
print("Instantiating complexes...")
complexes = self.factory(self.remove_2feats)
torch.save(self.collate(complexes, self.max_dim), self.processed_paths[0])
| 3,221 | 34.021739 | 101 | py |
cwn | cwn-main/exp/parser.py | import os
import time
import argparse
from definitions import ROOT_DIR
def get_parser():
parser = argparse.ArgumentParser(description='CWN experiment.')
parser.add_argument('--seed', type=int, default=43,
help='random seed to set (default: 43, i.e. the non-meaning of life))')
parser.add_argument('--start_seed', type=int, default=0,
help='The initial seed when evaluating on multiple seeds.')
parser.add_argument('--stop_seed', type=int, default=9,
help='The final seed when evaluating on multiple seeds.')
parser.add_argument('--device', type=int, default=0,
help='which gpu to use if any (default: 0)')
parser.add_argument('--model', type=str, default='sparse_cin',
help='model, possible choices: cin, dummy, ... (default: cin)')
parser.add_argument('--use_coboundaries', type=str, default='False',
help='whether to use coboundary features for up-messages in sparse_cin (default: False)')
parser.add_argument('--include_down_adj', action='store_true',
help='whether to use lower adjacencies (i.e. CIN++ networks) (default: False)')
# ^^^ here we explicitly pass it as string as easier to handle in tuning
parser.add_argument('--indrop_rate', type=float, default=0.0,
help='inputs dropout rate for molec models(default: 0.0)')
parser.add_argument('--drop_rate', type=float, default=0.0,
help='dropout rate (default: 0.5)')
parser.add_argument('--drop_position', type=str, default='lin2',
help='where to apply the final dropout (default: lin2, i.e. _before_ lin2)')
parser.add_argument('--nonlinearity', type=str, default='relu',
help='activation function (default: relu)')
parser.add_argument('--readout', type=str, default='sum',
help='readout function (default: sum)')
parser.add_argument('--final_readout', type=str, default='sum',
help='final readout function (default: sum)')
parser.add_argument('--readout_dims', type=int, nargs='+', default=(0, 1, 2),
help='dims at which to apply the final readout (default: 0 1 2, i.e. nodes, edges, 2-cells)')
parser.add_argument('--jump_mode', type=str, default=None,
help='Mode for JK (default: None, i.e. no JK)')
parser.add_argument('--graph_norm', type=str, default='bn', choices=['bn', 'ln', 'id'],
help='Normalization layer to use inside the model')
parser.add_argument('--lr', type=float, default=0.001,
help='learning rate (default: 0.001)')
parser.add_argument('--lr_scheduler', type=str, default='StepLR',
help='learning rate decay scheduler (default: StepLR)')
parser.add_argument('--lr_scheduler_decay_steps', type=int, default=50,
help='number of epochs between lr decay (default: 50)')
parser.add_argument('--lr_scheduler_decay_rate', type=float, default=0.5,
help='strength of lr decay (default: 0.5)')
parser.add_argument('--lr_scheduler_patience', type=float, default=10,
help='patience for `ReduceLROnPlateau` lr decay (default: 10)')
parser.add_argument('--lr_scheduler_min', type=float, default=0.00001,
help='min LR for `ReduceLROnPlateau` lr decay (default: 1e-5)')
parser.add_argument('--num_layers', type=int, default=5,
help='number of message passing layers (default: 5)')
parser.add_argument('--emb_dim', type=int, default=64,
help='dimensionality of hidden units in models (default: 300)')
parser.add_argument('--batch_size', type=int, default=32,
help='input batch size for training (default: 32)')
parser.add_argument('--epochs', type=int, default=100,
help='number of epochs to train (default: 100)')
parser.add_argument('--num_workers', type=int, default=0,
help='number of workers (default: 0)')
parser.add_argument('--dataset', type=str, default="PROTEINS",
help='dataset name (default: PROTEINS)')
parser.add_argument('--task_type', type=str, default='classification',
help='task type, either (bin)classification, regression or isomorphism (default: classification)')
parser.add_argument('--eval_metric', type=str, default='accuracy',
help='evaluation metric (default: accuracy)')
parser.add_argument('--iso_eps', type=int, default=0.01,
help='Threshold to define (non-)isomorphism')
parser.add_argument('--minimize', action='store_true',
help='whether to minimize evaluation metric or not')
parser.add_argument('--max_dim', type=int, default="2",
help='maximum cellular dimension (default: 2, i.e. two_cells)')
parser.add_argument('--max_ring_size', type=int, default=None,
help='maximum ring size to look for (default: None, i.e. do not look for rings)')
parser.add_argument('--result_folder', type=str, default=os.path.join(ROOT_DIR, 'exp', 'results'),
help='filename to output result (default: None, will use `scn/exp/results`)')
parser.add_argument('--exp_name', type=str, default=str(time.time()),
help='name for specific experiment; if not provided, a name based on unix timestamp will be '+\
'used. (default: None)')
parser.add_argument('--dump_curves', action='store_true',
help='whether to dump the training curves to disk')
parser.add_argument('--untrained', action='store_true',
help='whether to skip training')
parser.add_argument('--fold', type=int, default=None,
help='fold index for k-fold cross-validation experiments')
parser.add_argument('--folds', type=int, default=None,
help='The number of folds to run on in cross validation experiments')
parser.add_argument('--init_method', type=str, default='sum',
help='How to initialise features at higher levels (sum, mean)')
parser.add_argument('--train_eval_period', type=int, default=10,
help='How often to evaluate on train.')
parser.add_argument('--tune', action='store_true', help='Use the tuning indexes')
parser.add_argument('--flow_points', type=int, default=400,
help='Number of points to use for the flow experiment')
parser.add_argument('--flow_classes', type=int, default=3,
help='Number of classes for the flow experiment')
parser.add_argument('--train_orient', type=str, default='default',
help='What orientation to use for the training complexes')
parser.add_argument('--test_orient', type=str, default='default',
help='What orientation to use for the testing complexes')
parser.add_argument('--fully_orient_invar', action='store_true',
help='Whether to apply torch.abs from the first layer')
parser.add_argument('--use_edge_features', action='store_true',
help="Use edge features for molecular graphs")
parser.add_argument('--simple_features', action='store_true',
help="Whether to use only a subset of original features, specific to ogb-mol*")
parser.add_argument('--early_stop', action='store_true', help='Stop when minimum LR is reached.')
parser.add_argument('--paraid', type=int, default=0,
help='model id')
parser.add_argument('--preproc_jobs', type=int, default=2,
help='Jobs to use for the dataset preprocessing. For all jobs use "-1".'
'For sequential processing (no parallelism) use "1"')
return parser
def validate_args(args):
"""Performs dataset-dependent sanity checks on the supplied args."""
if args.dataset == 'CSL':
assert args.model == 'embed_sparse_cin'
assert args.task_type == 'classification'
assert not args.minimize
assert args.lr_scheduler == 'ReduceLROnPlateau'
assert args.eval_metric == 'accuracy'
assert args.fold is not None
assert not args.simple_features
assert args.graph_norm == 'ln'
elif args.dataset == 'RING-TRANSFER' or args.dataset == 'RING-LOOKUP':
assert args.model == 'ring_sparse_cin' or args.model == 'gin_ring'
assert args.task_type == 'classification'
assert not args.minimize
assert args.lr_scheduler == 'None'
assert args.eval_metric == 'accuracy'
assert args.fold is None
assert not args.simple_features
assert args.max_ring_size is not None and args.max_ring_size > 3
if args.model == 'ring_sparse_cin':
assert args.graph_norm == 'id'
if args.model == 'gin_ring':
assert args.graph_norm == 'bn'
elif args.dataset.startswith('ZINC'):
assert args.model.startswith('embed')
if args.model == 'embed_cin++':
assert args.include_down_adj is True
assert args.task_type == 'regression'
assert args.minimize
assert args.eval_metric == 'mae'
assert args.lr_scheduler == 'ReduceLROnPlateau'
assert not args.simple_features
elif args.dataset in ['MOLHIV', 'MOLPCBA', 'MOLTOX21', 'MOLTOXCAST', 'MOLMUV',
'MOLBACE', 'MOLBBBP', 'MOLCLINTOX', 'MOLSIDER', 'MOLESOL',
'MOLFREESOLV', 'MOLLIPO']:
assert args.model == 'ogb_embed_sparse_cin' or args.model == "ogb_embed_cin++"
if args.model == 'ogb_embed_cin++':
assert args.include_down_adj is True
assert args.eval_metric == 'ogbg-'+args.dataset.lower()
assert args.jump_mode is None
if args.dataset in ['MOLESOL', 'MOLFREESOLV', 'MOLLIPO']:
assert args.task_type == 'mse_regression'
assert args.minimize
else:
assert args.task_type == 'bin_classification'
assert not args.minimize
elif args.dataset.startswith('sr'):
assert args.model in ['sparse_cin', 'mp_agnostic']
assert args.eval_metric == 'isomorphism'
assert args.task_type == 'isomorphism'
assert args.jump_mode is None
assert args.drop_rate == 0.0
assert args.untrained
assert args.nonlinearity == 'elu'
assert args.readout == 'sum'
assert args.final_readout == 'sum'
assert not args.simple_features
elif args.dataset == 'FLOW' or args.dataset == 'OCEAN':
assert args.model == 'edge_orient' or args.model == 'edge_mpnn'
assert args.eval_metric == 'accuracy'
assert args.task_type == 'classification'
assert args.jump_mode is None
assert args.drop_rate == 0.0
assert not args.untrained
assert not args.simple_features
assert not args.minimize
| 11,349 | 59.695187 | 126 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.