exchangealgebra 0.7.0.0 → 0.7.0.1
raw patch · 8 files changed
+460/−65 lines, 8 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
Files
- ChangeLog.md +21/−0
- README.md +1/−1
- exchangealgebra.cabal +1/−1
- src/ExchangeAlgebra/Algebra/Core/Representation.hs +163/−49
- src/ExchangeAlgebra/Algebra/Value.hs +18/−4
- src/ExchangeAlgebra/Journal/Core/Representation.hs +17/−9
- test/Algebra/AccumSpec.hs +87/−1
- test/Algebra/ProjWildcardSpec.hs +152/−0
ChangeLog.md view
@@ -1,5 +1,26 @@ # Changelog for ExchangeAlgebra +## 0.7.0.1 - 2026-11-28++### Fixed++- Base relabeling, `Journal.toAlg`, and `toList` now give equal results for+ equal inputs when distinct bases or notes share a hash. Previously, the+ insertion order of those keys could change the resulting term sequences+ and the `Binary` bytes for equal algebras with multiple terms. Traversals+ now visit equal-hash keys in `Ord` order. Inputs without hash collisions+ produce the same results as before.++- Exact `MoneyDecimal` sums now retain the largest number of decimal places+ among their inputs. This applies to `sumValues`, `balanceBy`, `balanceMapBy`,+ `projNetNorm`, `bar`, and balances used in accounting transfers and closing.+ Previously, a zero input or an intermediate sum of zero could make the+ number of trailing zeros depend on the order of addition, which for a+ ledger follows the hashes of its bases. Results still compare equal under+ `==`.+ Calculated amounts may show more trailing zeros with `show` and have+ different `Binary` bytes.+ ## 0.7.0.0 - 2026-11-27 ### Added
README.md view
@@ -22,7 +22,7 @@ ```yaml # stack.yaml extra-deps:- - exchangealgebra-0.6.1.1+ - exchangealgebra-0.7.0.0 ``` ```yaml
exchangealgebra.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: exchangealgebra-version: 0.7.0.0+version: 0.7.0.1 synopsis: Exchange Algebra for bookkeeping and economic simulation description: Exchange Algebra is an algebraic description of bookkeeping developed by Hiroshi Deguchi. This package represents bookkeeping entries as members of a redundant algebra. The Hat direction of a base expresses a decrease, and the Not direction expresses an increase. Term values are non-negative. The package provides journals with notes, accounting operations such as closing, transfers, trial balances, and financial statements, CSV input and output, and a state-space framework for economic simulation. See the README for a guide and the changelog for migration notes. category: Accounting, Finance, Math
src/ExchangeAlgebra/Algebra/Core/Representation.hs view
@@ -48,6 +48,8 @@ , nullPair , pairAppend , pairUnion+ , foldlHashMapByHash+ , foldrHashMapByHash , emptyAxisPosting , insertAxisPosting , queryAxisPosting@@ -107,6 +109,7 @@ import qualified Data.List as L (foldl', sort, sortOn, any) import Prelude hiding (map, head, filter, tail, traverse, mapM)+import Data.Hashable (Hashable, hash) import qualified Data.HashMap.Strict as Map import qualified Data.IntMap.Strict as IntMap import qualified Data.IntSet as IntSet@@ -117,8 +120,82 @@ import qualified Data.Maybe as Maybe import Control.DeepSeq import GHC.Stack (HasCallStack)+import GHC.Exts (oneShot) import qualified Data.Binary as Binary +-- | State of a collision check in hash map traversal order.+data HashScan+ = NoHash+ | PreviousHash {-# UNPACK #-} !Int+ | CollisionFound++-- | Check adjacent hashes before choosing the fold.+-- Keys with the same hash are adjacent in 'Map.HashMap' traversal order.+{-# INLINE hasHashCollision #-}+hasHashCollision :: Hashable k => Map.HashMap k v -> Bool+hasHashCollision entries = case Map.foldlWithKey' step NoHash entries of+ CollisionFound -> True+ _ -> False+ where+ step CollisionFound _ _ = CollisionFound+ step NoHash key _ = PreviousHash (hash key)+ step (PreviousHash previous) key _+ | current == previous = CollisionFound+ | otherwise = PreviousHash current+ where+ current = hash key++-- | The pending entry and any other entries with the same hash.+data HashRun k v+ = EmptyRun -- ^ No entry has been read yet.+ | HashRun !Int !k v [(k, v)] -- ^ The list is allocated only for collisions.++-- | Fold in 'Map.HashMap' traversal order, sorting keys with the same hash+-- by 'Ord'. Equal maps therefore yield the same sequence of entries. Hashes+-- can vary across @hashable@ versions and machines, so the order among keys+-- with different hashes can vary across those environments.+-- After checking adjacent hashes, maps with distinct hashes use+-- 'Map.foldrWithKey'. Maps with a collision sort each run of equal-hash keys.+{-# INLINE foldrHashMapByHash #-}+foldrHashMapByHash :: (Hashable k, Ord k) => (k -> v -> a -> a) -> a -> Map.HashMap k v -> a+foldrHashMapByHash combine ~initial entries+ | hasHashCollision entries = foldrHashMapCollisions combine initial entries+ | otherwise = Map.foldrWithKey combine initial entries++-- | Buffer and sort equal-hash runs in a map with collisions.+{-# INLINE foldrHashMapCollisions #-}+foldrHashMapCollisions :: (Hashable k, Ord k) => (k -> v -> a -> a) -> a -> Map.HashMap k v -> a+foldrHashMapCollisions combine ~initial entries = Map.foldrWithKey step finish entries EmptyRun+ where+ step key value ~next = oneShot $ \pending ->+ let !keyHash = hash key+ in case pending of+ EmptyRun -> next (HashRun keyHash key value [])+ HashRun previousHash firstKey firstValue collisions+ | keyHash == previousHash ->+ next (HashRun previousHash firstKey firstValue ((key, value) : collisions))+ | otherwise ->+ emit firstKey firstValue collisions (next (HashRun keyHash key value []))++ finish EmptyRun = initial+ finish (HashRun _ firstKey firstValue collisions) =+ emit firstKey firstValue collisions initial++ emit key value [] ~rest = combine key value rest+ emit key value collisions ~rest =+ foldr (\(entryKey, entryValue) -> combine entryKey entryValue) rest+ (L.sortOn fst ((key, value) : collisions))++-- | Strict left fold in the traversal order of 'foldrHashMapByHash'.+-- Maps with distinct hashes use @Map.foldlWithKey'@ after the collision check.+{-# INLINE foldlHashMapByHash #-}+foldlHashMapByHash :: (Hashable k, Ord k) => (a -> k -> v -> a) -> a -> Map.HashMap k v -> a+foldlHashMapByHash combine initial entries+ | hasHashCollision entries = foldrHashMapCollisions step id entries initial+ | otherwise = Map.foldlWithKey' combine initial entries+ where+ step key value ~next = oneShot $ \ !acc -> next $! combine acc key value+ -- * Algebra ------------------------------------------------------------ ------------------------------------------------------------------@@ -551,9 +628,12 @@ -- | Serialize an algebra in the 0.5 wire layout (tag 0 = 'Zero', tag 1 = -- one posting, tag 2 = the per-base map with each t'Pair' in sequence order).--- Tag 2 writes blocks in the base 'Map.HashMap' traversal order, so equal--- algebras can have different byte sequences across versions of @hashable@.--- Compare decoded values to check equality.+-- Tag 2 writes blocks in 'Map.HashMap' traversal order, with equal-hash keys+-- sorted by 'Ord'. Within one environment, equal algebras with the same+-- tag have identical byte sequences when their component encoders agree+-- on equal values. Equal algebras can have different byte sequences across+-- versions of @hashable@ or when one is a singleton and the other a one-term+-- map. Compare decoded values for equality. -- -- Decoding is a construction boundary, like '.@': it fails on a value for -- which 'valueError' is 'Just' (negative or non-finite), on a tag-1 posting@@ -583,7 +663,7 @@ put (Liner m _ _ _ _ _) = do Binary.put (2 :: Int) Binary.put (Map.size m :: Int)- Map.foldrWithKey+ foldrHashMapByHash (\bp p k -> Binary.put bp >> Binary.put p >> k) (pure ()) m@@ -1056,12 +1136,14 @@ where productValue = x * v x .* (Liner ms idx bpToId idToBp nextBpId allIds)- | any isZeroValue (vals scaled) = filter (not . isZeroValue . _val) scaled- | otherwise = scaled+ | any hasZero scaledPairs = filter (not . isZeroValue . _val) scaled+ | otherwise = scaled where- scaled = Liner- (Map.map (mapPair (x *)) ms)- idx bpToId idToBp nextBpId allIds+ scaledPairs = Map.map (mapPair (x *)) ms+ scaled = Liner scaledPairs idx bpToId idToBp nextBpId allIds+ hasZero (HatOne value) = isZeroValue value+ hasZero (NotOne value) = isZeroValue value+ hasZero (PairSeq hs ns) = any isZeroValue hs || any isZeroValue ns norm Zero = 0 norm (v:@_) = roundAccum (addAccum v emptyAccum)@@ -1142,17 +1224,27 @@ -- | Visit full-base pairs without rebuilding every posting's base.+-- The fold visits keys with the same hash in 'Ord' order. foldPairs :: (HatVal n, HatBaseClass b) => (a -> BasePart b -> Pair n -> a) -> a -> Alg n b -> a {-# INLINE foldPairs #-}-foldPairs _ initial Zero = initial-foldPairs collect initial (value :@ postingBase)+foldPairs = foldPairsWith foldlHashMapByHash++-- | Visit each full-base pair in the order provided by the supplied map fold.+{-# INLINE foldPairsWith #-}+foldPairsWith :: (HatVal n, HatBaseClass b)+ => ((a -> BasePart b -> Pair n -> a) -> a -> Map.HashMap (BasePart b) (Pair n) -> a)+ -> (a -> BasePart b -> Pair n -> a)+ -> a+ -> Alg n b+ -> a+foldPairsWith _ _ initial Zero = initial+foldPairsWith _ collect initial (value :@ postingBase) | isZeroValue value = initial- | isHat postingBase = collect initial (base postingBase)- (HatOne value)- | otherwise = collect initial (base postingBase)- (NotOne value)-foldPairs collect initial (Liner pairs _ _ _ _ _) = Map.foldlWithKey' collect initial pairs+ | isHat postingBase = collect initial (base postingBase) (HatOne value)+ | otherwise = collect initial (base postingBase) (NotOne value)+foldPairsWith foldMapPairs collect initial (Liner pairs _ _ _ _ _) =+ foldMapPairs collect initial pairs -- | Exact Not-minus-Hat residual for one complete base. netPairState :: HatVal n => Pair n -> Accum n@@ -1173,7 +1265,7 @@ {-# INLINE postNetStates #-} postNetStates keyOf algebra = (mkAlgFromMap retained, totals) where- (!retained, !totals) = foldPairs collect (Map.empty, M.empty) algebra+ (!retained, !totals) = foldPairsWith Map.foldlWithKey' collect (Map.empty, M.empty) algebra collect (!unchanged, !amounts) basePart pair = let state = netPairState pair select side magnitude = case keyOf (merge side basePart) of@@ -1191,26 +1283,27 @@ ------------------------------------------------------------------ -- | Returns the value of each term, as a list.------ Complexity: O(s) (s is the total number of scalar entries)+-- The traversal visits keys with the same hash in 'Ord' order.+-- Complexity: linear in the number of terms, plus sorting within collisions. vals :: (HatVal v, HatBaseClass b) => Alg v b -> [v] vals Zero = [] vals (v:@_) = [v] vals (Liner m _ _ _ _ _) = reverse $- Map.foldl'- (foldPair (flip (:)) (flip (:)))+ foldlHashMapByHash+ (\values _ -> foldPair (flip (:)) (flip (:)) values) [] m -- | Returns the hat base of each term, as a list.------ Complexity: O(s) (s is the total number of scalar entries)+-- The traversal visits keys with the same hash in 'Ord' order before+-- prepending terms to the result.+-- Complexity: linear in the number of terms, plus sorting within collisions. bases :: (HatVal v, HatBaseClass b) => Alg v b -> [b] bases Zero = [] bases (_:@b) = [b]-bases (Liner m _ _ _ _ _) = Map.foldlWithKey' f [] m+bases (Liner m _ _ _ _ _) = foldlHashMapByHash f [] m where f :: (HatVal v, HatBaseClass b) => [b] -> BasePart b -> Pair v -> [b] f xs b = foldPair (g Hat b) (g Not b) xs@@ -1288,7 +1381,9 @@ | otherwise = mergeAlgMapIfNonZero acc (f k v) -- | Returns the list of terms.--- Complexity: O(s) (s is the total number of scalar entries)+-- The traversal visits keys with the same hash in 'Ord' order before+-- prepending terms to the result. Equal algebras produce equal lists.+-- Complexity: linear in the number of terms, plus sorting within collisions. -- -- >>> toList (10.@Hat:<(Yen) .+ 10.@Hat:<(Dollar) .+ Zero :: Alg Double (HatBase CountUnit)) -- [10.00:@Hat:<Dollar,10.00:@Hat:<Yen]@@ -1297,9 +1392,18 @@ -- >>> toList Zero :: [Alg Double (HatBase CountUnit)] -- [] toList :: (HatVal v, HatBaseClass b) => Alg v b -> [Alg v b]-toList Zero = []-toList (v:@b) = [v`Single`b]-toList (Liner m _ _ _ _ _) = Map.foldlWithKey' f [] m+toList = toListWith foldlHashMapByHash++-- | Collect terms by prepending each term in the supplied map traversal.+{-# INLINE toListWith #-}+toListWith :: (HatVal v, HatBaseClass b)+ => (([Alg v b] -> BasePart b -> Pair v -> [Alg v b])+ -> [Alg v b] -> Map.HashMap (BasePart b) (Pair v) -> [Alg v b])+ -> Alg v b+ -> [Alg v b]+toListWith _ Zero = []+toListWith _ (v :@ b) = [v `Single` b]+toListWith foldMapPairs (Liner m _ _ _ _ _) = foldMapPairs f [] m where f :: (HatVal v, HatBaseClass b) => [Alg v b] -> BasePart b -> Pair v -> [Alg v b] f xs b (HatOne v) = g Hat b xs v@@ -1313,7 +1417,10 @@ | otherwise = (v `Single` (merge h b)):ys {-# INLINE foldEntries #-}--- | Strict left fold over scalar entries without building an intermediate list.+-- | Strict left fold over scalar entries, sorting only runs of base keys+-- with the same hash by 'Ord'. For lawful values and bases, @x == y@ implies+-- @foldEntries f initial x == foldEntries f initial y@ for the same step+-- and initial accumulator, whenever the step respects equality. -- -- This is the implementation vehicle for the universal extension from the free -- commutative monoid of entries when each step acts through an associative,@@ -1333,7 +1440,7 @@ | isZeroValue v = acc | otherwise = f acc v b foldEntries f !acc (Liner m _ _ _ _ _) =- Map.foldlWithKey' step acc m+ foldlHashMapByHash step acc m where step :: acc -> BasePart b -> Pair v -> acc step !acc0 !bp pair =@@ -1346,11 +1453,14 @@ {-# INLINE toASCList #-} -- | Complexity: O(s log s), dominated by sorting the list representation. toASCList :: (HatVal v, HatBaseClass b) => Alg v b -> [Alg v b]-toASCList = L.sort . toList+toASCList = L.sort . toListWith Map.foldlWithKey' --- | map--- Complexity: O(s + c), where s is traversed scalar entries and c is transformed output size.+-- | Transform each term with a function that returns one term.+-- The traversal orders base keys with the same hash by 'Ord', so equal+-- inputs give equal results with the same equality-preserving function.+-- Complexity: O(s + c), plus sorting within collisions, where s is the+-- number of input terms and c is the number of output terms. -- Typed alternatives: 'mapPosting' and 'mapMaybePosting'. -- -- >>> type Test = Alg Double (HatBase CountUnit)@@ -1378,7 +1488,7 @@ in case isZeroValue v2 of True -> Zero False -> (v2 `Single` b2)-map f (Liner m _ _ _ _ _) = mkAlgFromMap $ (Map.foldrWithKey (p f) dnilMap m) Map.empty+map f (Liner m _ _ _ _ _) = mkAlgFromMap $ foldrHashMapByHash (p f) dnilMap m Map.empty where {-# INLINE dnilMap #-} dnilMap = id@@ -1465,8 +1575,10 @@ => (v -> b -> (v2, b2)) -> Alg v b -> Alg v2 b2 mapPosting f = mapMaybePosting (\v b -> Just (f v b)) --- | Map every posting to zero or one posting. A 'Nothing' drops the posting;--- a zero value is normalized as by '(.@)'.+-- | Map each term to at most one term. 'Nothing' drops the term, and '(.@)'+-- normalizes a zero value. The traversal orders base keys with the same hash+-- by 'Ord', so equal inputs give equal results with the same+-- equality-preserving function. mapMaybePosting :: (HatVal v, HatVal v2, HatBaseClass b, HatBaseClass b2) => (v -> b -> Maybe (v2, b2)) -> Alg v b -> Alg v2 b2 mapMaybePosting _ Zero = Zero@@ -1474,7 +1586,7 @@ Nothing -> Zero Just (v2, b2) -> v2 .@ b2 mapMaybePosting f (Liner m _ _ _ _ _) =- mkAlgFromMap $ Map.foldrWithKey addPair id m Map.empty+ mkAlgFromMap $ foldrHashMapByHash addPair id m Map.empty where {-# INLINE addPair #-} addPair bp (HatOne v) accDMap = mapOne (merge Hat bp) id v . accDMap@@ -1570,12 +1682,13 @@ -- relabelling (always on exact values). -- -- In particular, @mapBasePart f (bar x) == bar (mapBasePart f x)@ is false in--- general: distinct source bases may collide only after relabelling. When--- collisions occur, @pairAppend@ preserves every value but the resulting--- sequence order is a representation detail determined by @HashMap@ traversal;--- callers must not attach semantics to it.+-- general: distinct source bases may merge after relabeling. The traversal+-- preserves every value and visits source keys with the same hash in 'Ord'+-- order. For lawful values and bases and an equality-preserving @f@,+-- @x == y@ implies @mapBasePart f x == mapBasePart f y@. ----- Complexity: O(n) over distinct base keys (rebuilds the posting index once).+-- Complexity: linear in the number of base keys, plus sorting within+-- collisions. The posting index is rebuilt once. -- -- >>> type T = Alg Double (HatBase CountUnit) -- >>> mapBasePart id (10.@Hat:<Yen :: T) :: T@@ -1589,7 +1702,7 @@ mapBasePart f (v :@ b) = singleton v (merge (hat b) (f (base b))) mapBasePart f (Liner m _ _ _ _ _) = mkAlgFromMap $- Map.foldlWithKey'+ foldlHashMapByHash (\acc bp p -> Map.insertWith pairAppend (f bp) p acc) Map.empty m@@ -1628,11 +1741,12 @@ -- Zero-valued entries are skipped, as in 'foldEntries'. Well-formedness of the -- algebras returned by @h@ (non-negative, finite values) is the caller's -- responsibility: build them with @(.\@)@ rather than the raw constructor.--- The sequence order of the result is a representation detail determined by--- the traversal of @x@; callers must not attach semantics to it.+-- The traversal visits base keys with the same hash in 'Ord' order.+-- For lawful values and bases and an equality-preserving @h@,+-- @x == y@ implies @extendBy h x == extendBy h y@. ----- Complexity: O(n · cost(h)) plus the cost of the @('.+')@ merges, in one--- pass over the entries.+-- Complexity: O(n · cost(h)) plus the cost of the @('.+')@ merges and+-- sorting within collisions, in one pass over the entries. -- -- >>> type T = Alg Double (HatBase CountUnit) -- >>> let split v b = (v / 2) .@ b .+ (v / 2) .@ b :: T@@ -1967,7 +2081,7 @@ {-# SPECIALIZE balanceMapBy :: (HatBaseClass b, Ord k) => (BasePart b -> Maybe k) -> Alg MoneyDecimal b -> M.Map k MoneyDecimal #-} balanceMapBy :: (HatVal v, HatBaseClass b, Ord k) => (BasePart b -> Maybe k) -> Alg v b -> M.Map k v-balanceMapBy keyOf = M.map roundAccum . foldPairs collect M.empty+balanceMapBy keyOf = M.map roundAccum . foldPairsWith Map.foldlWithKey' collect M.empty where collect totals basePart pair = case keyOf basePart of Nothing -> totals@@ -2026,7 +2140,7 @@ {-# SPECIALIZE netPairMapBy :: (HatBaseClass b, Ord k) => (BasePart b -> Maybe k) -> Alg MoneyDecimal b -> M.Map k (MoneyDecimal, MoneyDecimal) #-} netPairMapBy :: (HatVal v, HatBaseClass b, Ord k) => (BasePart b -> Maybe k) -> Alg v b -> M.Map k (v, v)-netPairMapBy keyOf = M.map finish . foldPairs collect M.empty+netPairMapBy keyOf = M.map finish . foldPairsWith Map.foldlWithKey' collect M.empty where collect totals basePart pair = case keyOf basePart of Nothing -> totals
src/ExchangeAlgebra/Algebra/Value.hs view
@@ -323,13 +323,15 @@ {-# INLINE showValue #-} showValue (MoneyDecimal x) = show x - -- Decimal addition is exact, so the state is the signed exact sum.+ -- The signed exact sum keeps the largest number of decimal places among+ -- its inputs, even when it is zero. Order and grouping preserve both+ -- the number of places and the mantissa. newtype Accum MoneyDecimal = MoneyDecimalAccum Decimal- emptyAccum = MoneyDecimalAccum 0+ emptyAccum = MoneyDecimalAccum (Decimal 0 0) addAccum (MoneyDecimal value) (MoneyDecimalAccum total) =- MoneyDecimalAccum (total + value)+ MoneyDecimalAccum (addDecimalAtMaxPlaces total value) mergeAccum (MoneyDecimalAccum left) (MoneyDecimalAccum right) =- MoneyDecimalAccum (left + right)+ MoneyDecimalAccum (addDecimalAtMaxPlaces left right) negateAccum (MoneyDecimalAccum value) = MoneyDecimalAccum (negate value) signAccum (MoneyDecimalAccum value) = Just (compare value 0) roundAccum (MoneyDecimalAccum value) = MoneyDecimal value@@ -350,6 +352,18 @@ roundRational (ToMultipleOf (MoneyDecimal unit)) value | unit > 0 = Just (MoneyDecimal (fromInteger (round (value / toRational unit)) * unit)) | otherwise = Nothing++-- | Add exact mantissas at the larger number of decimal places, including for zeros.+addDecimalAtMaxPlaces :: Decimal -> Decimal -> Decimal+addDecimalAtMaxPlaces (Decimal leftPlaces leftMantissa) (Decimal rightPlaces rightMantissa)+ | leftPlaces < rightPlaces =+ Decimal rightPlaces (rescale leftMantissa (rightPlaces - leftPlaces) + rightMantissa)+ | leftPlaces > rightPlaces =+ Decimal leftPlaces (leftMantissa + rescale rightMantissa (leftPlaces - rightPlaces))+ | otherwise = Decimal leftPlaces (leftMantissa + rightMantissa)+ where+ rescale 0 _ = 0+ rescale mantissa extraPlaces = mantissa * 10 ^ extraPlaces -- 'Binary'/'Hashable' are defined here (not orphan) because 'Data.Decimal' ships -- neither, and 'Alg'/t'Journal' serialization and the binary spill path require
src/ExchangeAlgebra/Journal/Core/Representation.hs view
@@ -395,7 +395,8 @@ else Map.insert k dMerged dAcc -- | Serialize a journal as its note count followed by each note and its--- algebra. Decoding checks each algebra as the 'Alg' instance does and fails+-- algebra. Notes with the same hash are encoded in 'Ord' order.+-- Decoding checks each algebra as the 'Alg' instance does and fails -- on a repeated note. The encoder never writes a note whose algebra is zero -- (see the normal form on t'Journal'); the decoder drops one written by an -- older encoder instead of rejecting the bytes, so they still decode.@@ -410,7 +411,7 @@ put j = do let !m = toMap j Binary.put (Map.size m :: Int)- Map.foldrWithKey+ EA.foldrHashMapByHash (\n alg k -> Binary.put n >> Binary.put alg >> k) (pure ()) m@@ -505,7 +506,7 @@ _ -> showParen (d > 3) (showsGroups groups) where m = toMap js- groups = reverse $ Map.foldrWithKey collectGroup [] m+ groups = reverse $ EA.foldrHashMapByHash collectGroup [] m collectGroup k a acc | not (isPlank k) && Prelude.null (EA.toASCList a) = acc@@ -581,7 +582,7 @@ (.^) = map (.^) (.+) = mappend (.*) x = map ((.*) x)- norm = norm . toAlg+ norm = norm . EA.unionsMerge . materializeMap (.-) x = map (.-) (gather plank x) compress = map compress @@ -733,12 +734,16 @@ ------------------------------------------------------------------ -- | Combine all notes into a single algebra. -- Merge both layers of each note first, then combine notes in the traversal--- order of the resulting @HashMap@.+-- order of the resulting @HashMap@, visiting notes with the same hash in+-- 'Ord' order. For lawful notes, bases, and values, equal 'toMap' results+-- imply equal 'toAlg' results. ----- Complexity: O(total number of base keys across all notes)+-- The cost includes the merges and sorting each run of equal-hash notes. toAlg :: (HatVal v, HatBaseClass b, Note n) => Journal n v b -> Alg v b-toAlg = EA.unionsMerge . materializeMap+toAlg = EA.mkAlgFromMap . EA.foldlHashMapByHash mergeNote Map.empty . materializeMap+ where+ mergeNote acc _ algebra = EA.mergeAlgMap acc algebra ------------------------------------------------------------------ -- | Apply function f to the entry of each Note in the Journal.@@ -1040,9 +1045,12 @@ postFromNetBy keyOf post journal = retained .+ M.foldlWithKey' (\result key state -> result .+ post key (roundAccum state)) mempty amounts where- (nonfinite, amounts) = EA.postNetStates keyOf (toAlg journal)+ (nonfinite, amounts) = EA.postNetStates keyOf (EA.unionsMerge (materializeMap journal)) retained | HSet.null nonfiniteBases = mempty | otherwise = map (EA.filter (\entry -> HSet.member (base (EA._hatBase entry)) nonfiniteBases)) journal- nonfiniteBases = HSet.fromList (Prelude.map base (EA.bases nonfinite))+ nonfiniteBases = case nonfinite of+ EA.Zero -> HSet.empty+ _ :@ basis -> HSet.singleton (base basis)+ EA.Liner { EA._realg = pairs } -> Map.keysSet pairs
test/Algebra/AccumSpec.hs view
@@ -1,7 +1,7 @@ {-# LANGUAGE ScopedTypeVariables #-} -- | Exact accumulator laws in the Algebra layer. The public HatVal methods--- are observed against Rational, with no tolerance and no readout operations.+-- are observed against Rational and the decimal representation. -- Generators cover binary64 boundaries and decimal scales before the fixed cases. module Algebra.AccumSpec (runTests) where @@ -9,12 +9,18 @@ import qualified Data.Decimal as Decimal import Data.Hashable (hashWithSalt) import qualified Data.List as List+import qualified Data.Map.Strict as Map import Data.Maybe (isJust) import Data.Ratio ((%), denominator)+import qualified Data.Ratio as Ratio+import qualified Data.Text as Text+import Data.Word (Word8) import GHC.Float (castDoubleToWord64, castWord64ToDouble) import System.Exit (exitFailure) import Test.QuickCheck hiding (label) +import qualified ExchangeAlgebra.Algebra as Algebra+import ExchangeAlgebra.Algebra (Hat(..), HatBase((:<)), (.@)) import ExchangeAlgebra.Algebra.Value ( HatVal(..) , MoneyDecimal(..)@@ -299,6 +305,49 @@ , rationalRoundAccum negate state === negate expected ] +-- | Observe both decimal fields because numeric equality ignores trailing zeros.+decimalParts :: MoneyDecimal -> (Word8, Integer)+decimalParts (MoneyDecimal (Decimal.Decimal places coefficient)) = (places, coefficient)++-- | Compare exact sums and decimal representations across orders and groupings.+propDecimalPlaces :: Property+propDecimalPlaces =+ forAll (chooseInt (0, 20) >>= flip vectorOf genDecimal) $ \values ->+ forAll genDecimal $ \value ->+ -- Include a nonempty sum that cancels in every trial.+ let terms = value : values+ in conjoin [checkPlaces values, checkPlaces (terms ++ map negate terms)]+ where+ checkPlaces values = forAll (shuffle values) $ \permuted ->+ forAll (chooseInt (0, length values)) $ \firstCut ->+ forAll (chooseInt (firstCut, length values)) $ \secondCut ->+ let (left, rest) = splitAt firstCut permuted+ (middle, right) = splitAt (secondCut - firstCut) rest+ first = accumulate left+ second = accumulate middle+ third = accumulate right+ states =+ [ accumulate values+ , accumulate permuted+ , mergeAccum (mergeAccum first second) third+ , mergeAccum first (mergeAccum second third)+ ]+ places = maximum (0 : map (fst . decimalParts) values)+ exact = sum (map toRational values)+ coefficient = Ratio.numerator (exact * fromInteger (10 ^ places))+ parts = (places, coefficient)+ expectedSplit+ | exact > 0 = Just [parts]+ | otherwise = Nothing+ in conjoin+ [ conjoin+ [ decimalParts (roundAccum state) === parts+ , fmap (map decimalParts) (splitAccum state) === expectedSplit+ , exactAccum state === Just exact+ ]+ | state <- states+ ]+ -- * Fixed boundaries -- | Integer overflow, cancellation, two decimal places, subnormals, and greedy splits.@@ -462,6 +511,41 @@ check "decimal zero hash" (hashWithSalt salt (MoneyDecimal (Decimal.Decimal 0 0))) (hashWithSalt salt (MoneyDecimal (Decimal.Decimal 255 0))) +-- | Check decimal places in accumulator outputs and grouped ledger balances.+testDecimalPlaces :: IO ()+testDecimalPlaces = do+ let one = MoneyDecimal (Decimal.Decimal 2 100)+ two = MoneyDecimal (Decimal.Decimal 1 20)+ zero = MoneyDecimal (Decimal.Decimal 2 0)+ positiveOne = addAccum one emptyAccum+ negativeOne = negateAccum positiveOne+ positiveTwo = addAccum two emptyAccum+ baseNames = map Text.pack ["a", "b", "c"]+ terms = [(one, Not), (one, Hat), (two, Not)]+ forM_ (List.permutations terms) $ \assignment -> do+ let ledger = Algebra.fromList (zipWith makeTerm assignment baseNames)+ balances = Algebra.balanceMapBy (const (Just ())) ledger+ check ("balanceMapBy decimal places " ++ show assignment)+ (Map.singleton () "2.00") (fmap show balances)+ forM_ (List.permutations [positiveOne, negativeOne, positiveTwo]) $ \states -> do+ let leftGrouped = List.foldl' mergeAccum emptyAccum states+ rightGrouped = foldr mergeAccum emptyAccum states+ forM_ [leftGrouped, rightGrouped] $ \state -> do+ check "roundAccum decimal places" "2.00" (show (roundAccum state))+ check "splitAccum decimal places" (Just ["2.00"])+ (fmap (map show) (splitAccum state))+ let cancelled = mergeAccum positiveOne negativeOne+ check "zero state decimal places" (2, 0) (decimalParts (roundAccum cancelled))+ check "negated zero state decimal places" (2, 0)+ (decimalParts (roundAccum (negateAccum cancelled)))+ check "empty state decimal places" (0, 0)+ (decimalParts (roundAccum (emptyAccum :: Accum MoneyDecimal)))+ check "sumValues leading zero decimal places" "2.00" (show (sumValues [zero, two]))+ check "sumValues trailing zero decimal places" "2.00" (show (sumValues [two, zero]))+ putStrLn "[PASS] accum decimal places in fixed cases and balanceMapBy"+ where+ makeTerm (value, side) name = value .@ (side :< name)+ -- | B1 and P1 at adjacent floating values and an unbounded decimal magnitude. testPostingBoundaries :: IO () testPostingBoundaries = do@@ -494,11 +578,13 @@ testFloatingBoundaries testSpecialValues testDecimalBoundaries+ testDecimalPlaces testPostingBoundaries propertyCheck "Double A1-A6/A5'/E1/E2/T3/S1/V1-V3/B1/P1" (propFiniteLaws genFinite) propertyCheck "MoneyDouble A1-A6/A5'/E1/E2/T3/S1/V1-V3/B1/P1" (propFiniteLaws (MoneyDouble <$> genFinite)) propertyCheck "MoneyDecimal A1-A6/A5'/E1/T3/S1/V1-V3/B1/P1" (propFiniteLaws genDecimal)+ propertyCheck "MoneyDecimal decimal places across orders and groupings" propDecimalPlaces propertyCheck "A5 greedy Double split" propGreedySplit propertyCheck "T1/T3 decimal unit and ties" propDecimalUnit propertyCheck "T2 decimal representability" propDecimalNearest
test/Algebra/ProjWildcardSpec.hs view
@@ -8,6 +8,8 @@ module Algebra.ProjWildcardSpec (runTests) where import qualified Data.Binary as Binary+import qualified Data.Binary.Put as Binary+import qualified Data.HashMap.Strict as HashMap import Data.Time ( Day(ModifiedJulianDay) , TimeOfDay(..) , fromGregorian@@ -19,12 +21,14 @@ import Control.Monad (unless) import qualified Data.List as List import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe, listToMaybe) import Data.Text (Text) import System.Exit (exitFailure) import Test.QuickCheck hiding (label) import ExchangeAlgebra.Algebra hiding (map, filter) import qualified ExchangeAlgebra.Algebra as Algebra import ExchangeAlgebra.Algebra.Element (matchesQuery)+import qualified ExchangeAlgebra.Algebra.Internal as Internal import qualified ExchangeAlgebra.Algebra.Transfer as Transfer import ExchangeAlgebra.Algebra.Value (MoneyDecimal) import qualified ExchangeAlgebra.Journal as Journal@@ -265,6 +269,151 @@ put (FixtureId number) = Binary.put number get = FixtureId <$> Binary.get +instance Journal.Note FixtureId where+ plank = FixtureId 0++-- | An algebra whose distinct concrete bases have the same hash.+type CollisionAlg = Alg Double (HatBase (Wild FixtureId))++-- | A destination shared by every generated source base.+collisionTarget :: Wild FixtureId+collisionTarget = Exactly (FixtureId 0)++-- | Compare the results of reading or relabeling equal algebras.+collisionOrderLaws :: CollisionAlg -> CollisionAlg -> [(String, Bool)]+collisionOrderLaws left right =+ [ ("equal inputs", left == right)+ , ("mapBasePart", agrees (mapBasePart (const collisionTarget) :: CollisionAlg -> CollisionAlg))+ , ("map", agrees (Algebra.map (\(value :@ basis) -> relabel value basis)))+ , ("mapMaybePosting", agrees (mapMaybePosting (\value basis -> Just (value, target basis))))+ , ("extendBy", agrees (extendBy relabel))+ , ("transferEntries", transferAgrees)+ , ("foldEntries", agrees (foldEntries (\terms value basis -> (value, basis) : terms) []))+ , ("toList", agrees toList)+ , ("vals", agrees vals)+ , ("bases", agrees bases)+ ]+ where+ agrees observeResult = observeResult left == observeResult right+ target basis = hat basis :< collisionTarget+ relabel value basis = value .@ target basis+ transferAgrees = case Transfer.mkTransferRules+ [Transfer.TransferRule (HatNot :< Wild) (HatNot :< collisionTarget) Transfer.Relabel] of+ Left _ -> False+ Right rules ->+ let apply = Transfer.transferEntries rules+ in case (apply left, apply right) of+ (Right actual, Right expected) -> actual == expected+ _ -> False++-- | Change the interleaving of whole base groups, keeping each group's sequence.+genCollisionLedgers :: Gen (CollisionAlg, CollisionAlg)+genCollisionLedgers = frequency [(4, multipleBases), (1, oneTerm)]+ where+ multipleBases = do+ count <- chooseInt (2, 8)+ groups <- traverse genTerms [1 .. count]+ reordered <- shuffle groups+ pure (fromList (concat groups), fromList (concat reordered))++ genTerms identifier = listOf1 $ do+ side <- elements [Hat, Not]+ value <- fromIntegral <$> chooseInt (1, 10)+ pure (value .@ side :< Exactly (FixtureId identifier))++ oneTerm = do+ firstValue <- fromIntegral <$> chooseInt (1, 10)+ secondValue <- fromIntegral <$> chooseInt (1, 10)+ side <- elements [Hat, Not]+ let basis = side :< Exactly (FixtureId 1)+ single = (firstValue + secondValue) .@ basis+ composed = bar (firstValue .@ basis .+ secondValue .@ basis)+ pure (single, composed)++-- | Check equal-hash placement, including equal one-term values of different shapes.+testCollisionOrder :: IO ()+testCollisionOrder = do+ assertTest "Hash collisions: distinct concrete bases have equal hashes"+ (first /= second && hash first == hash second)+ mapM_ (\(operation, success) -> assertTest ("Hash collisions: " ++ operation) success)+ (collisionOrderLaws left right)+ assertEqual "Hash collisions: foldEntries visits equal-hash bases in Ord order"+ [second, first] (foldEntries (\keys _ basis -> base basis : keys) [] right)+ assertEqual "Hash collisions: Alg Binary bytes" (Binary.encode left) (Binary.encode right)+ quickProperty "Hash collisions: equal Alg readouts and encodings" $+ forAll genCollisionLedgers $ \(before, after) ->+ let keys = case before of+ Internal.Liner {} -> HashMap.keys (Internal._realg before)+ _ -> []+ hashes = map hash keys+ colliding = length hashes /= length (List.nub hashes)+ in checkCoverage+ $ cover 60 colliding "multiple colliding bases"+ $ cover 10 (not colliding) "equal singleton and one-term map"+ $ conjoin+ ([counterexample operation (property success)+ | (operation, success) <- collisionOrderLaws before after]+ ++ [Binary.encode before === Binary.encode after | colliding])+ where+ first = Exactly (FixtureId 1)+ second = Exactly (FixtureId 2)+ left = 1 .@ Not :< first .+ 2 .@ Not :< second :: CollisionAlg+ right = 2 .@ Not :< second .+ 1 .@ Not :< first :: CollisionAlg++-- | Reversing two equal-hash notes leaves journal readouts equal.+testNoteCollisionOrder :: IO ()+testNoteCollisionOrder = do+ assertEqual "Hash collisions: equal journal maps" (Journal.toMap left) (Journal.toMap right)+ assertEqual "Hash collisions: Journal.toAlg" (Journal.toAlg left) (Journal.toAlg right)+ assertEqual "Hash collisions: Journal Binary bytes" (Binary.encode left) (Binary.encode right)+ assertEqual "Hash collisions: Journal Show" (show left) (show right)+ where+ first = (1 .@ Not :< collisionTarget :: CollisionAlg) Journal..| FixtureId 1+ second = (2 .@ Not :< collisionTarget :: CollisionAlg) Journal..| FixtureId 2+ left = first .+ second+ right = second .+ first++-- | Preserve the previous output direction and wire order for distinct hashes.+testDistinctHashOrder :: IO ()+testDistinctHashOrder = do+ assertTest "Distinct hashes: fixture keys do not collide"+ (length hashes == length (List.nub hashes))+ assertEqual "Distinct hashes: toList keeps reverse HashMap key order"+ (reverse keys) outputKeys+ assertEqual "Distinct hashes: Alg Binary retains HashMap traversal order"+ previousBytes (Binary.encode algebra)+ assertTest "Distinct hashes: fixture notes do not collide"+ (length noteHashes == length (List.nub noteHashes))+ assertEqual "Distinct hashes: Journal.toAlg retains HashMap traversal order"+ (unionsMerge notes) (Journal.toAlg journal)+ assertEqual "Distinct hashes: Journal Binary retains HashMap traversal order"+ previousJournalBytes (Binary.encode journal)+ where+ algebra = 1 .@ Hat :< Yen .+ 2 .@ Hat :< Yen .+ 3 .@ Not :< Yen+ .+ 4 .@ Not :< Dollar .+ 5 .@ Hat :< Amount :: Alg Double (HatBase CountUnit)+ entries = Internal._realg algebra+ keys = HashMap.keys entries+ hashes = map hash keys+ outputKeys = mapMaybe listToMaybe $ List.group $ map (base . _hatBase) (toList algebra)+ previousBytes = Binary.runPut $ do+ Binary.put (2 :: Int)+ Binary.put (HashMap.size entries)+ HashMap.foldrWithKey+ (\key pair remaining -> Binary.put key >> Binary.put pair >> remaining)+ (pure ())+ entries+ journal = (1 .@ Not :< Yen) Journal..| (3 :: Int)+ .+ (2 .@ Not :< Yen) Journal..| 1+ .+ (3 .@ Not :< Yen) Journal..| 2 :: Journal.Journal Int Double (HatBase CountUnit)+ notes = Journal.toMap journal+ noteHashes = map hash (HashMap.keys notes)+ previousJournalBytes = Binary.runPut $ do+ Binary.put (HashMap.size notes)+ HashMap.foldrWithKey+ (\note terms remaining -> Binary.put note >> Binary.put terms >> remaining)+ (pure ())+ notes+ -- | Compare exact coordinates, sides, and amounts independently of posting order. observeWild :: forall coordinates. (BaseClass coordinates, HasElementKeys coordinates) => Alg MoneyDecimal (HatBase coordinates)@@ -549,3 +698,6 @@ testWildAccountTitles testWildPayload testWildCalendarRegression+ testCollisionOrder+ testNoteCollisionOrder+ testDistinctHashOrder