Skip to content

Commit

Permalink
Add LICENSE, substitue setup.py with pyproject.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
giuluck committed Mar 5, 2024
1 parent eb78b24 commit c5d36c0
Show file tree
Hide file tree
Showing 10 changed files with 466 additions and 381 deletions.
35 changes: 35 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Main Workflow

on: [push, workflow_dispatch]

jobs:
test:
strategy:
fail-fast: false
matrix:
# * test on different operative systems
# * test minimal versions: python 3.10 + strict (minimal) requirements from 'requirements.txt'
# * test latest versions: python 3:x (latest) + latest requirements (eager) from 'pyproject.toml' (.)
os: ["windows-2022", "macos-13", "ubuntu-20.04"]
versions: [
["3.7.0", "-r requirements.txt"],
["3.8.0", "-r requirements.txt"],
["3.9.0", "-r requirements.txt"]
]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.versions[0] }}
- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install --upgrade pytest==8.0.2
pip install --upgrade ${{ matrix.versions[1] }}
- name: Print Versions
run: |
python --version
pip freeze
- name: Run Tests
run: pytest -rfP
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Luca Giuliani

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.
34 changes: 34 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# test using "pytest"
# build using "hatch build"
# publish using "hatch publish"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = 'causalgen'
version = '0.1.1'
requires-python = '>=3.10'
dependencies = [
'matplotlib>=3.7',
'networkx>=2.7',
'numpy>=1.22',
'pandas>=1.4'
]
description = 'Causalgen: a causal-based utility for data generation'
readme = { file = "README.md", content-type = "text/markdown" }
authors = [
{ name = 'Luca Giuliani', email = '[email protected]' },
{ name = 'University of Bologna - DISI' }
]
maintainers = [
{ name = 'Luca Giuliani', email = '[email protected]' }
]
license = { file = "LICENSE" }

[tool.hatch.build.targets.wheel]
packages = ["causalgen"]

[project.urls]
Repository = "https://github.com/giuluck/causalgen/"
9 changes: 5 additions & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
jupyter~=1.0.0
matplotlib~=3.7.2
networkx~=3.1
numpy~=1.25.1
pandas~=2.0.3
matplotlib==3.7.0
networkx==2.7.0
numpy==1.22.0
pandas==1.4.0
pytest~=8.0.2
26 changes: 0 additions & 26 deletions setup.py

This file was deleted.

62 changes: 62 additions & 0 deletions test/test_generation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import unittest

import numpy as np

from causalgen import Generator
from causalgen.variables import Node
from test.test_utils import DISTRIBUTIONS, SIZE


class TestGeneration(unittest.TestCase):
def test_distributions(self):
for dist, (kw1, kw2) in DISTRIBUTIONS.items():
dg, rand = Generator(seed=0), np.random.default_rng(0)
# 1. retrieve operations and check consistency of generator result
dg_dist, np_dist = getattr(dg, dist), rand.normal if dist == 'noise' else getattr(rand, dist)
node = dg_dist(**kw1, hidden=False, name='node')
vec = np_dist(**kw2, size=SIZE)
self.assertIsInstance(node, Node, f"Dist '{dist}': generator should return a Node instance")
# 2. generate the node value and check that the two vectors coincide
val = dg.generate(SIZE)['node'].values
self.assertListEqual(list(val), list(vec), f"Dist '{dist}': wrong value returned")

def test_random(self):
dg, rand = Generator(), np.random.default_rng(0)
# test None seed on init and reset
self.assertIs(Generator(seed=None).random, np.random, f"None seed should return np.random generator")
self.assertIs(dg.reset_seed(seed=None).random, np.random, f"None seed should return np.random generator")
# test rng seed on init and reset
self.assertIs(Generator(seed=rand).random, rand, f"Rng seed should the given generator")
self.assertIs(dg.reset_seed(seed=rand).random, rand, f"Rng seed should the given generator")
# test int seed on init and reset
for gen in [Generator(0), dg.reset_seed(0)]:
gv = gen.random.random(size=SIZE)
rv = np.random.default_rng(0).random(size=SIZE)
self.assertListEqual(list(gv), list(rv), f"Int seed should return the same vectors")

# noinspection PyPep8Naming
def test_generation(self):
dg, rand = Generator(seed=0), np.random.default_rng(0)
# correct values
h = rand.uniform(size=SIZE)
z = rand.binomial(n=1, p=0.5, size=SIZE)
noise_1 = rand.normal(size=SIZE)
noise_2 = rand.normal(size=SIZE)
x = (2 * z - 1) * h + 0.01 * noise_1
y = (x ** 2) * (0.01 * noise_2 + 1)
# generator nodes
H = dg.uniform(hidden=True, name='h')
Z = dg.binomial(hidden=False, name='z')
X = dg.descendant((2 * Z - 1) * H + 0.01 * dg.noise(), name='x')
dg.descendant((X ** 2) * (0.01 * dg.noise() + 1), name='y')
# check that generated values are correct
df = dg.generate(num=SIZE, hidden=True)
self.assertTrue(np.allclose(df['h'], h), f"Wrong values for 'h'")
self.assertTrue(np.allclose(df['z'], z), f"Wrong values for 'z'")
self.assertTrue(np.allclose(df['noise_1'], noise_1), f"Wrong values for 'noise_1'")
self.assertTrue(np.allclose(df['noise_2'], noise_2), f"Wrong values for 'noise_2'")
self.assertTrue(np.allclose(df['x'], x), f"Wrong values for 'x'")
self.assertTrue(np.allclose(df['y'], y), f"Wrong values for 'y'")
# check that hidden=False returns visible nodes only
df = dg.generate(num=SIZE, hidden=False)
self.assertListEqual(['z', 'x', 'y'], list(df.columns), f"Wrong nodes returned by generation")
110 changes: 110 additions & 0 deletions test/test_nodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import unittest

import numpy as np

from causalgen import Generator
from causalgen.variables import Node
from test.test_utils import ALIASES, SIZE


class TestNodes(unittest.TestCase):
def test_sources(self):
dg = Generator()
for operator, (alias, kwargs) in ALIASES.items():
operation = getattr(dg, operator)
# check that source node with given name is correctly built
node = operation(**kwargs, name=operator)
self.assertEqual(node.name, operator, f"Node was created with wrong name")
self.assertIn(node, dg.nodes, f"Node was not inserted in generator structure")
# check that node with same name raises an exception
with self.assertRaises(AssertionError):
operation(**kwargs, name=operator)
# check that source nodes without names are correctly named
for i in range(3):
node = operation(**kwargs)
self.assertEqual(node.name, f"{alias}_{i + 1}", f"Node was created with wrong name")
self.assertIn(node, dg.nodes, f"Node was not inserted in generator structure")
# check signature assertion in custom sources
with self.assertRaises(AssertionError):
dg.custom(lambda: np.empty(1))
with self.assertRaises(AssertionError):
dg.custom(lambda a, b: np.empty(1))

# noinspection PyPep8Naming
def test_descendants(self):
dg, rand = Generator(seed=0), np.random.default_rng(0)
# create sources
A = dg.normal(hidden=False, name='a')
vA = rand.normal(size=SIZE)
self.assertIs(A.hidden, False, f"Node A should be visible")
self.assertIs(A.visible, True, f"Node A should be visible")
B = dg.integers(hidden=True, name='b')
vB = rand.integers(0, 1, endpoint=True, size=SIZE)
self.assertIs(B.hidden, True, f"Node B should be hidden")
self.assertIs(B.visible, False, f"Node B should be hidden")
Ext = Node(generator=None, func=lambda: np.empty(1), parents=set(), hidden=False, name='ext')
# create correct descendants
C = dg.descendant(lambda a, b: a + b, noise=None, hidden=False, name='c')
self.assertIs(C.hidden, False, f"Node C should be visible")
self.assertIs(C.visible, True, f"Node C should be visible")
self.assertEqual(C.name, 'c', f"Node was created with wrong name")
self.assertIn(C, dg.nodes, f"Node was not inserted in generator structure")
D = dg.descendant(lambda x, y: x + y, noise=None, hidden=True, parents=[A, B], name='d')
self.assertIs(D.hidden, True, f"Node D should be hidden")
self.assertIs(D.visible, False, f"Node D should be hidden")
self.assertEqual(D.name, 'd', f"Node was created with wrong name")
self.assertIn(D, dg.nodes, f"Node was not inserted in generator structure")
Var_1 = dg.descendant(lambda x, y: x + y, noise=0.1, hidden=False, parents=['a', 'b'])
self.assertIs(Var_1.hidden, False, f"Node Var_1 should be visible")
self.assertIs(Var_1.visible, True, f"Node Var_1 should be visible")
self.assertEqual(Var_1.name, 'var_1', f"Node was created with wrong name")
self.assertIn(Var_1, dg.nodes, f"Node was not inserted in generator structure")
Var_2 = dg.descendant(A + B, noise=None, hidden=True)
self.assertIs(Var_2.hidden, True, f"Node Var_2 should be hidden")
self.assertIs(Var_2.visible, False, f"Node Var_2 should be hidden")
self.assertEqual(Var_2.name, 'var_2', f"Node was created with wrong name")
self.assertIn(Var_2, dg.nodes, f"Node was not inserted in generator structure")
Var_3 = dg.descendant(A + B, noise=0.1, hidden=False)
self.assertIs(Var_3.hidden, False, f"Node Var_3 should be visible")
self.assertIs(Var_3.visible, True, f"Node Var_3 should be visible")
self.assertEqual(Var_3.name, 'var_3', f"Node was created with wrong name")
self.assertIn(Var_3, dg.nodes, f"Node was not inserted in generator structure")
# check generated values (and noises)
df = dg.generate(num=SIZE, hidden=True)
n1, n3 = rand.normal(scale=0.1, size=SIZE), rand.normal(scale=0.1, size=SIZE)
self.assertListEqual(list(df['a']), list(vA), f"Wrong samples from 'a'")
self.assertListEqual(list(df['b']), list(vB), f"Wrong samples from 'b'")
self.assertListEqual(list(df['c']), list(vA + vB), f"Wrong operation from 'c'")
self.assertListEqual(list(df['d']), list(vA + vB), f"Wrong operation from source 'd'")
self.assertListEqual(list(df['var_1']), list(vA + vB + n1), f"Wrong operation from 'var_1'")
self.assertListEqual(list(df['var_2']), list(vA + vB), f"Wrong operation from 'var_2'")
self.assertListEqual(list(df['var_3']), list(vA + vB + n3), f"Wrong operation from 'var_3'")
# create wrong descendants
with self.assertRaises(AssertionError):
dg.descendant(lambda a, b: a + b, name='c')
with self.assertRaises(AssertionError):
dg.descendant(lambda a, b, ext: a + b + ext)
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y: x + y, name='c', parents=[A, B])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y: x + y, parents=[A, B, Ext])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y, z: x + y + z, parents=[A, B])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y, z: x + y + z, parents=[A, B, Ext])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y: x + y, name='c', parents=['a', 'b'])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y: x + y, parents=['a', 'b', 'ext'])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y, z: x + y + z, parents=['a', 'b'])
with self.assertRaises(AssertionError):
dg.descendant(lambda x, y, z: x + y + z, parents=['a', 'b', 'ext'])
with self.assertRaises(AssertionError):
dg.descendant(A + B, name='c')
with self.assertRaises(AssertionError):
dg.descendant(A + B, parents=[A, B])
with self.assertRaises(AssertionError):
dg.descendant(A + B, parents=['a', 'b'])
with self.assertRaises(AssertionError):
dg.descendant(A + B + Ext)
Loading

0 comments on commit c5d36c0

Please sign in to comment.