Code Monkey home page Code Monkey logo

emmy's Introduction

Emmy

Algebraic structures and related operations for Nim.

logo

Status

This library was extracted from a separate project, and will require some polish. Expect the API to change (hopefully for the better!) until further notice. :-)

There is not too much in terms of documentation yet, but you can see the tests to get an idea.

Algebraic structures

The first building block for Emmy are definitions for common algebraic structures, such as monoids or Euclidean rings. Such structures are encoded using concepts, which means that they can be used as generic constraints (say, a certain operation only works over fields).

The definitions for those concepts follow closely the usual definitions in mathematics:

type
  AdditiveMonoid* = concept x, y, type T
    x + y is T
    zero(T) is T
  AdditiveGroup* = concept x, y, type T
    T is AdditiveMonoid
    -x is T
    x - y is T
  MultiplicativeMonoid* = concept x, y, type T
    x * y is T
    id(T) is T
  MultiplicativeGroup* = concept x, y, type T
    T is MultiplicativeMonoid
    x / y is T
  Ring* = concept type T
    T is AdditiveGroup
    T is MultiplicativeMonoid
  EuclideanRing* = concept x, y, type T
    T is Ring
    x div y is T
    x mod y is T
  Field* = concept type T
    T is Ring
    T is MultiplicativeGroup

We notice a couple of ways where the mechanical encoding strays from the mathematical idea:

  • first, the definition above only requires the existence of appropriate operations, and we cannot say anything in general about the various axioms that these structures satisfy, such as associativity or commutativity;
  • second, the division is mathematically only defined for non-zero denominators, but we have no way to enforce this at the level of types.

Default instances

A few common data types implement the above concepts:

  • all standard integer types (int, int32, int64) are instances of EuclideanRing;
  • Emmy depends on bigints, and BigInt is an EuclideanRing as well;
  • all float types are instances of Field;
  • TableRef[K, V] is an instance of AdditiveMonoid, provided V is.

The latter uses the sum on values corresponding to the same keys, so that for instance

{ "a": 1, "b": 2 }.newTable + { "c": 3, "b": 5 }.newTable == { "a": 1, "c": 3, "b": 7 }.newTable

Making your own algebraic structures

In order to make your data types a member of these concepts, just give definitions for the appropriate operations.

The line zero(type(x)) is type(x) may look confusing at first. This means that - in order for a type A to be a monoid - you have to implement a function of type proc(x: typedesc[A]): A. For instance, for int we have

proc zero*(x: typedesc[int]): int = 0

and this allows us to call it like

zero(int) # returns 0

A similar remark holds for id(type(x)) is type(x).

Cartesian products

The product of two additive (resp. multiplicative) monoids is itself an additive (resp. multiplicative) monoid. The same holds for additive groups and for rings (but not for fields!).

Emmy defines suitable operations on pairs of elements, so that tuples with two elements live in an appropriate algebraic structure, provided each component does. Hence, for instance, (int, float64) is a ring, and

(1, 2.0) + (3, 4.0) == (4, 6.0)
(1, 2.0) * (3, 4.0) == (3, 8.0)
zero((int, float64)) == (0, 0.0)

For products with more than two factors, you can either define your own instances or work recursively, using the isomorphism between (A, B, C) and ((A, B), C).

Modular rings

To be documented, see tests

Fraction rings

To be documented, see tests

Primality

To be documented, see tests

Polynomials

To be documented, see tests

Linear algebra

To be documented, see tests

Finite fields

To be documented, see tests

Normal forms of matrices

To be documented, see tests

emmy's People

Contributors

andreaferretti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

emmy's Issues

Very slow and memory inefficient algorithm used to sieve primes...

This repo's implementation of sieveUpTo called by primesUpTo* has got to be one of the slowest and most wasteful of memory implementation of the Sieve of Eratosthenes of any I have seen...

The problems are as follows:

  1. In using IntSet as it's base storage, it uses multiple bytes per stored composite entry, which memory use is so high that it can't sieve even up to a billion as it consumes Gigabytes of memory over that range as it uses many bytes per entry for every composite number over the range.
  2. It doesn't even implement the very simple optimization of sieving "odds-only" so there are about two and a half times more culling operations than necessary (and twice as much memory is required for all the unused evens).
  3. Composite culling operation execution overheads are atrocious (although constant time on the average) as it must perform a hashing operation each time.
  4. Cache associativity is also atrocious as it is skipping over this huge linked memory storage.

It has the single advantage of being short. However, it can't sieve to a billion using a reasonably amount of RAM memory and even if it could it would take about a minute or so.

A much better short implementation which greatly reduces the memory consumption such that very large ranges can be sieved (although still somewhat slowly due to the hashing) is as follows:

# compile with "-d:release -d:danger"

import tables
 
type PrimeType = uint64
proc primesHashTable(): iterator(): PrimeType {.closure.} =
  iterator output(): PrimeType {.closure.} =
    # some initial values to avoid race and reduce initializations...
    yield 2.PrimeType; yield 3.PrimeType; yield 5.PrimeType; yield 7.PrimeType
    var h = initTable[PrimeType,PrimeType]()
    var n = 9.PrimeType
    let bps = primesHashTable()
    var bp = bps() # advance past 2
    bp = bps(); var q = bp * bp # to initialize with 3
    while true:
      if n >= q:
        let inc = bp + bp
        h.add(n + inc, inc)
        bp = bps(); q = bp * bp
      elif h.hasKey(n):
        var inc: PrimeType
        discard h.take(n, inc)
        var nxt = n + inc
        while h.hasKey(nxt): nxt += inc # ensure no duplicates
        h.add(nxt, inc)
      else: yield n
      n += 2.PrimeType
  output

# tested as...
from times import epochTime

let limit = 100_000_000.PrimeType
let start = epochTime()
let iter = primesHashTable()
var count = 0
for p in iter():
  if p > limit: break else: count.inc
let elpsd = (epochTime() - start) * 1000.0
echo "Found ", count, " primes up to ", limit, " in ", elpsd, " milliseconds."

This is an "incremental" Odds-Only Sieve of Eratosthenes and only stores a hash entry for each of the base primes up to the square root of the current iteration value (determined automatically by the recursive secondary base primes feed). It still takes about a minute to count the number of primes to a billion, but at least it doesn't take an excessive amount of memory to do so. Its output also doesn't consume memory as it is just an iterator over the "incrementally" found primes.

If being so short isn't a consideration, the Page Segmented Bit-Packed Odds-Only Unbounded Sieve of Eratosthenes from RosettaCode is fast as in only taking about a second to sieve to a billion, consumes even less memory, and can even relatively easily have multi-threading added, but is over a hundred lines of code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.