cglsmr.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /*
  2. Tideland Common Go Library - Sorting and Map/Reduce
  3. Copyright (C) 2009-2011 Frank Mueller / Oldenburg / Germany
  4. Redistribution and use in source and binary forms, with or
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. Redistributions of source code must retain the above copyright notice, this
  8. list of conditions and the following disclaimer.
  9. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. Neither the name of Tideland nor the names of its contributors may be
  13. used to endorse or promote products derived from this software without
  14. specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  19. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  20. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  22. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  23. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  24. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  25. THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. package cgl
  28. //--------------------
  29. // IMPORTS
  30. //--------------------
  31. import (
  32. "hash/adler32"
  33. "sort"
  34. )
  35. //--------------------
  36. // CONTROL VALUES
  37. //--------------------
  38. // Threshold for switching from parallel to sequential quick sort.
  39. var QuickSortParallelThreshold int = 4095
  40. // Threshold for switching from sequential quick sort to insertion sort.
  41. var QuickSortSequentialThreshold int = 63
  42. //--------------------
  43. // HELPING FUNCS
  44. //--------------------
  45. // Simple insertion sort for smaller data collections.
  46. func insertionSort(data sort.Interface, lo, hi int) {
  47. for i := lo + 1; i < hi+1; i++ {
  48. for j := i; j > lo && data.Less(j, j-1); j-- {
  49. data.Swap(j, j-1)
  50. }
  51. }
  52. }
  53. // Get the median based on Tukey's ninther.
  54. func median(data sort.Interface, lo, hi int) int {
  55. m := (lo + hi) / 2
  56. d := (hi - lo) / 8
  57. // Move median into the middle.
  58. mot := func(ml, mm, mh int) {
  59. if data.Less(mm, ml) {
  60. data.Swap(mm, ml)
  61. }
  62. if data.Less(mh, mm) {
  63. data.Swap(mh, mm)
  64. }
  65. if data.Less(mm, ml) {
  66. data.Swap(mm, ml)
  67. }
  68. }
  69. // Get low, middle, and high median.
  70. if hi-lo > 40 {
  71. mot(lo+d, lo, lo+2*d)
  72. mot(m-d, m, m+d)
  73. mot(hi-d, hi, hi-2*d)
  74. }
  75. // Get combined median.
  76. mot(lo, m, hi)
  77. return m
  78. }
  79. // Partition the data based on the median.
  80. func partition(data sort.Interface, lo, hi int) (int, int) {
  81. med := median(data, lo, hi)
  82. idx := lo
  83. data.Swap(med, hi)
  84. for i := lo; i < hi; i++ {
  85. if data.Less(i, hi) {
  86. data.Swap(i, idx)
  87. idx++
  88. }
  89. }
  90. data.Swap(idx, hi)
  91. return idx - 1, idx + 1
  92. }
  93. // Sequential quicksort using itself recursively.
  94. func sequentialQuickSort(data sort.Interface, lo, hi int) {
  95. if hi-lo > QuickSortSequentialThreshold {
  96. // Use sequential quicksort.
  97. plo, phi := partition(data, lo, hi)
  98. sequentialQuickSort(data, lo, plo)
  99. sequentialQuickSort(data, phi, hi)
  100. } else {
  101. // Use insertion sort.
  102. insertionSort(data, lo, hi)
  103. }
  104. }
  105. // Parallel quicksort using itself recursively
  106. // and concurrent.
  107. func parallelQuickSort(data sort.Interface, lo, hi int, done chan bool) {
  108. if hi-lo > QuickSortParallelThreshold {
  109. // Parallel QuickSort.
  110. plo, phi := partition(data, lo, hi)
  111. partDone := make(chan bool)
  112. go parallelQuickSort(data, lo, plo, partDone)
  113. go parallelQuickSort(data, phi, hi, partDone)
  114. // Wait for the end of both sorts.
  115. <-partDone
  116. <-partDone
  117. } else {
  118. // Sequential QuickSort.
  119. sequentialQuickSort(data, lo, hi)
  120. }
  121. // Signal that it's done.
  122. done <- true
  123. }
  124. //--------------------
  125. // PARALLEL QUICKSORT
  126. //--------------------
  127. func Sort(data sort.Interface) {
  128. done := make(chan bool)
  129. go parallelQuickSort(data, 0, data.Len()-1, done)
  130. <-done
  131. }
  132. //--------------------
  133. // BASIC KEY/VALUE TYPES
  134. //--------------------
  135. // Data processing is based on key/value pairs.
  136. type KeyValue struct {
  137. Key string
  138. Value interface{}
  139. }
  140. // Channel for the transfer of key/value pairs.
  141. type KeyValueChan chan *KeyValue
  142. // Slice of key/value channels.
  143. type KeyValueChans []KeyValueChan
  144. // Map a key/value pair, emit to the channel.
  145. type MapFunc func(*KeyValue, KeyValueChan)
  146. // Reduce the key/values of the first channel, emit to the second channel.
  147. type ReduceFunc func(KeyValueChan, KeyValueChan)
  148. // Channel for closing signals.
  149. type SigChan chan bool
  150. //--------------------
  151. // HELPING FUNCS
  152. //--------------------
  153. // Close given channel after a number of signals.
  154. func closeSignalChannel(kvc KeyValueChan, size int) SigChan {
  155. sigChan := make(SigChan)
  156. go func() {
  157. ctr := 0
  158. for {
  159. <-sigChan
  160. ctr++
  161. if ctr == size {
  162. close(kvc)
  163. return
  164. }
  165. }
  166. }()
  167. return sigChan
  168. }
  169. // Perform the reducing.
  170. func performReducing(mapEmitChan KeyValueChan, reduceFunc ReduceFunc, reduceSize int, reduceEmitChan KeyValueChan) {
  171. // Start a closer for the reduce emit chan.
  172. sigChan := closeSignalChannel(reduceEmitChan, reduceSize)
  173. // Start reduce funcs.
  174. reduceChans := make(KeyValueChans, reduceSize)
  175. for i := 0; i < reduceSize; i++ {
  176. reduceChans[i] = make(KeyValueChan)
  177. go func(inChan KeyValueChan) {
  178. reduceFunc(inChan, reduceEmitChan)
  179. sigChan <- true
  180. }(reduceChans[i])
  181. }
  182. // Read map emitted data.
  183. for kv := range mapEmitChan {
  184. hash := adler32.Checksum([]byte(kv.Key))
  185. idx := hash % uint32(reduceSize)
  186. reduceChans[idx] <- kv
  187. }
  188. // Close reduce channels.
  189. for _, reduceChan := range reduceChans {
  190. close(reduceChan)
  191. }
  192. }
  193. // Perform the mapping.
  194. func performMapping(mapInChan KeyValueChan, mapFunc MapFunc, mapSize int, mapEmitChan KeyValueChan) {
  195. // Start a closer for the map emit chan.
  196. sigChan := closeSignalChannel(mapEmitChan, mapSize)
  197. // Start mapping goroutines.
  198. mapChans := make(KeyValueChans, mapSize)
  199. for i := 0; i < mapSize; i++ {
  200. mapChans[i] = make(KeyValueChan)
  201. go func(inChan KeyValueChan) {
  202. for kv := range inChan {
  203. mapFunc(kv, mapEmitChan)
  204. }
  205. sigChan <- true
  206. }(mapChans[i])
  207. }
  208. // Dispatch input data to map channels.
  209. idx := 0
  210. for kv := range mapInChan {
  211. mapChans[idx%mapSize] <- kv
  212. idx++
  213. }
  214. // Close mapping channels channel.
  215. for i := 0; i < mapSize; i++ {
  216. close(mapChans[i])
  217. }
  218. }
  219. //--------------------
  220. // MAP/REDUCE
  221. //--------------------
  222. // Simple map/reduce function.
  223. func MapReduce(inChan KeyValueChan, mapFunc MapFunc, mapSize int, reduceFunc ReduceFunc, reduceSize int) KeyValueChan {
  224. mapEmitChan := make(KeyValueChan)
  225. reduceEmitChan := make(KeyValueChan)
  226. // Perform operations.
  227. go performReducing(mapEmitChan, reduceFunc, reduceSize, reduceEmitChan)
  228. go performMapping(inChan, mapFunc, mapSize, mapEmitChan)
  229. return reduceEmitChan
  230. }
  231. //--------------------
  232. // RESULT SORTING
  233. //--------------------
  234. // Less function for sorting.
  235. type KeyValueLessFunc func(*KeyValue, *KeyValue) bool
  236. // Sortable set of key/value pairs.
  237. type SortableKeyValueSet struct {
  238. data []*KeyValue
  239. lessFunc KeyValueLessFunc
  240. }
  241. // Constructor for the sortable set.
  242. func NewSortableKeyValueSet(kvChan KeyValueChan, kvLessFunc KeyValueLessFunc) *SortableKeyValueSet {
  243. s := &SortableKeyValueSet{
  244. data: make([]*KeyValue, 0, 1024),
  245. lessFunc: kvLessFunc,
  246. }
  247. for kv := range kvChan {
  248. l := len(s.data)
  249. if l == cap(s.data) {
  250. tmp := make([]*KeyValue, l, l+1024)
  251. copy(tmp, s.data)
  252. s.data = tmp
  253. }
  254. s.data = s.data[0 : l+1]
  255. s.data[l] = kv
  256. }
  257. return s
  258. }
  259. // Sort interface: Return the len of the data.
  260. func (s *SortableKeyValueSet) Len() int {
  261. return len(s.data)
  262. }
  263. // Sort interface: Return which element is less.
  264. func (s *SortableKeyValueSet) Less(a, b int) bool {
  265. return s.lessFunc(s.data[a], s.data[b])
  266. }
  267. // Sort interface: Swap two elements.
  268. func (s *SortableKeyValueSet) Swap(a, b int) {
  269. s.data[a], s.data[b] = s.data[b], s.data[a]
  270. }
  271. // Return the data using a channel.
  272. func (s *SortableKeyValueSet) DataChan() KeyValueChan {
  273. kvChan := make(KeyValueChan)
  274. go func() {
  275. for _, kv := range s.data {
  276. kvChan <- kv
  277. }
  278. close(kvChan)
  279. }()
  280. return kvChan
  281. }
  282. // SortedMapReduce performes a map/reduce and sorts the result.
  283. func SortedMapReduce(inChan KeyValueChan, mapFunc MapFunc, mapSize int, reduceFunc ReduceFunc, reduceSize int, lessFunc KeyValueLessFunc) KeyValueChan {
  284. kvChan := MapReduce(inChan, mapFunc, mapSize, reduceFunc, reduceSize)
  285. s := NewSortableKeyValueSet(kvChan, lessFunc)
  286. Sort(s)
  287. return s.DataChan()
  288. }
  289. // KeyLessFunc compares the keys of two key/value
  290. // pairs. It returns true if the key of a is less
  291. // the key of b.
  292. func KeyLessFunc(a *KeyValue, b *KeyValue) bool {
  293. return a.Key < b.Key
  294. }
  295. /*
  296. EOF
  297. */