Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
langston-barrett committed Nov 20, 2022
0 parents commit 33f8ec1
Show file tree
Hide file tree
Showing 11 changed files with 577 additions and 0 deletions.
29 changes: 29 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: CI

on:
push:
branches:
- main
pull_request:

env:
# The NAME makes it easier to copy/paste snippets from other CI configs
NAME: fin-part-ord

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: cargo fmt -- --check
- run: |
rustup update
rustup component add clippy
- run: cargo clippy -- -D warnings

test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: cargo build
- run: env QUICKCHECK_GENERATOR_SIZE=32 cargo test
37 changes: 37 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Release

on:
push:
branches:
- release*
tags:
- 'v*'

env:
# The NAME makes it easier to copy/paste snippets from other CI configs
NAME: fin-part-ord

jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- uses: ncipollo/release-action@v1
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
with:
body: "See [CHANGELOG.md](https://github.com/langston-barrett/${NAME}/blob/main/CHANGELOG.md)"
draft: true
token: ${{ secrets.GITHUB_TOKEN }}

- name: Publish to crates.io
env:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
# Only push on actual release tags
PUSH: ${{ startsWith(github.ref, 'refs/tags/v') }}
run: |
if [[ ${PUSH} == true ]]; then
cargo publish --token ${CRATES_IO_TOKEN}
else
cargo publish --dry-run --token ${CRATES_IO_TOKEN}
fi
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
/Cargo.lock
23 changes: 23 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "fin-part-ord"
version = "0.0.0"
edition = "2021"
description = "Datatype for finite partial orders"
keywords = ["datatype", "finite", "partial-order", "ordering"]
authors = ["Langston Barrett <langston.barrett@gmail.com>"]
license = "MIT"
readme = "README.md"
homepage = "https://github.com/langston-barrett/fin-part-ord"
repository = "https://github.com/langston-barrett/fin-part-ord"

[dev-dependencies]
quickcheck = "1"

[features]
default = ["dag", "pairs"]
dag = ["dep:daggy", "dep:petgraph"]
pairs = []

[dependencies]
daggy = { optional = true, version = "0.8" }
petgraph = { optional = true, version = "0.6" }
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright © 2022 Brian Langston Barrett

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.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Finite Partial Orders

This crate provides a trait and datatypes for representing finite partial
orders. See [the API documentation][api] for more information.

[api]: https://docs.rs/fin-part-ord/0.1.0/
7 changes: 7 additions & 0 deletions nix/shell.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{ pkgs ? import <nixpkgs> { }
, unstable ? import <unstable> { }
}:

pkgs.mkShell {
nativeBuildInputs = [ pkgs.rust-analyzer pkgs.rustup ];
}
181 changes: 181 additions & 0 deletions src/dag.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
use std::collections::HashMap;
use std::hash::Hash;

use daggy::{Dag, NodeIndex, WouldCycle};
use petgraph::visit::Dfs;

use crate::r#trait::FinPartOrd;

/// A datatype for representing finite partial orders.
///
/// Stores partial order as a [`Dag`]. Doesn't store edges that can be deduced
/// by reflexivity or transitivity. Maintains the invariant that it always
/// represents a valid partial order, specifically that the set of edges obeys
/// antisymmetry, that is, forms a DAG.
#[derive(Clone, Debug)]
struct DagPartOrd<T> {
dag: Dag<T, ()>,
ids: HashMap<T, NodeIndex>,
}

impl<T> FinPartOrd<T> for DagPartOrd<T>
where
T: Clone,
T: Eq,
T: Hash,
{
type Error = WouldCycle<()>;

#[must_use]
fn empty() -> Self {
DagPartOrd {
dag: Dag::new(),
ids: HashMap::new(),
}
}

fn add(mut self, lo: T, hi: T) -> Result<Self, Self::Error> {
if lo == hi {
return Ok(self);
}
let lo_idx = match self.ids.get(&lo) {
Some(lo_idx) => *lo_idx,
None => {
let id = self.dag.add_node(lo.clone());
self.ids.insert(lo, id);
id
}
};
let hi_idx = match self.ids.get(&hi) {
Some(hi_idx) => *hi_idx,
None => {
let id = self.dag.add_node(hi.clone());
self.ids.insert(hi, id);
id
}
};
self.dag.add_edge(lo_idx, hi_idx, ())?;
Ok(self)
}

fn lt(&self, lo: &T, hi: &T) -> Result<bool, Self::Error> {
match (self.ids.get(lo), self.ids.get(hi)) {
(Some(lo_idx), Some(hi_idx)) => {
let mut dfs = Dfs::new(&self.dag, *lo_idx);
while let Some(n) = dfs.next(&self.dag) {
if n == *hi_idx {
return Ok(true);
}
}
Ok(false)
}
_ => Ok(false),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

use quickcheck::{quickcheck, Arbitrary, Gen};

impl Arbitrary for DagPartOrd<u8> {
fn arbitrary(g: &mut Gen) -> Self {
let mut ppo = DagPartOrd::empty();
let pairs = Vec::<(u8, u8)>::arbitrary(g);
for (x, y) in pairs {
if x <= y {
ppo = ppo.add(x, y).unwrap();
} else {
ppo = ppo.add(y, x).unwrap();
}
}
ppo
}

fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let mut iters = Vec::new();
match self.dag.graph().node_indices().next() {
Some(ix) => {
let mut new = self.clone();
new.dag.remove_node(ix);
iters.push(new);
}
None => (),
}
Box::new(iters.into_iter())
}
}

#[test]
fn empty() {
let _ = DagPartOrd::<()>::empty();
}

#[test]
fn push_unit() {
let unit = ();
DagPartOrd::empty().add(&unit, &unit).unwrap();
}

#[test]
fn strings() {
let mut ppo = DagPartOrd::empty();
ppo = ppo.add("x".to_string(), "y".to_string()).unwrap();
ppo = ppo.add("y".to_string(), "z".to_string()).unwrap();
assert!(ppo.le(&"x".to_string(), &"z".to_string()).unwrap());
}

quickcheck! {
fn antisymmetric_two(x: u8, y: u8) -> bool {
if x == y {
return true;
}
let mut ppo = DagPartOrd::empty();
ppo = ppo.add(&x, &y).unwrap();
println!("{:?}", ppo);
ppo.add(&y, &x).is_err()
}

fn transitive_three(x: u8, y: u8, z: u8) -> bool {
if x == z {
return true;
}
let mut ppo = DagPartOrd::empty();
ppo = ppo.add(x, y).unwrap();
ppo = ppo.add(y, z).unwrap();
ppo.le(&x, &z).unwrap()
}

fn add_le(ppo: DagPartOrd<u8>, x: u8, y: u8) -> bool {
match ppo.add(x, y) {
Err(_) => true,
Ok(ppo) => {
ppo.le(&x, &y).unwrap() && (!ppo.le(&y, &x).unwrap() || x == y)
}
}
}


fn reflexive(ppo: DagPartOrd<u8>, x: u8) -> bool {
ppo.le(&x, &x).unwrap()
}

fn antisymmetric(ppo: DagPartOrd<u8>, x: u8, y: u8) -> bool {
if ppo.le(&x, &y).unwrap() && ppo.le(&y, &x).unwrap() {
x == y
} else {
true
}
}

fn transitive(ppo: DagPartOrd<u8>, x: u8, y: u8, z: u8) -> bool {
if ppo.le(&x, &y).unwrap() && ppo.le(&y, &z).unwrap() {
ppo.le(&x, &z).unwrap()
} else {
true
}
}
}
}
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//! [FinPartOrd] is a trait for representing finite partial orders.
#[cfg(feature = "dag")]
mod dag;
#[cfg(feature = "dag")]
pub use dag::*;

#[cfg(feature = "pairs")]
mod pairs;
#[cfg(feature = "pairs")]
pub use pairs::*;

mod r#trait;
pub use r#trait::*;
Loading

0 comments on commit 33f8ec1

Please sign in to comment.