| 1 | // (c) 2020 Aaron Taylor <ataylor at subgeniuskitty dot com> |
| 2 | // See LICENSE.txt file for copyright and license details. |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "flag" |
| 8 | "fmt" |
| 9 | "log" |
| 10 | "os" |
| 11 | "runtime/pprof" |
| 12 | "sort" |
| 13 | "strconv" |
| 14 | ) |
| 15 | |
| 16 | // ============================================================================= |
| 17 | |
| 18 | // This program recognizes four types of numbers: |
| 19 | // - Surreal symbols, like those generated by Axiom 1. |
| 20 | // - Surreal numbers, like those selected by Axiom 2. |
| 21 | // - Reduced form numbers, per Definition 7. |
| 22 | // - Named form numbers, which are the equivalence classes induced by |
| 23 | // Definition 6, represented by the first representative reduced |
| 24 | // form number encountered at runtime. |
| 25 | // |
| 26 | // Although the surrealNumber type can represent any of these four types of |
| 27 | // numbers, the surrealUniverse contains only named form numbers. |
| 28 | // |
| 29 | // All equality tests (e.g. eq, geq, leq) in this program actually test for |
| 30 | // similarity per Definition 6. |
| 31 | |
| 32 | // ============================================================================= |
| 33 | |
| 34 | type surrealUniverse struct { |
| 35 | // The elements in this slice are stored in order according to Axiom 3. |
| 36 | // Thus, numbers[0] < numbers[1] < ... < numbers[n]. |
| 37 | numbers []surrealNumber |
| 38 | nextUniqueID uint |
| 39 | } |
| 40 | |
| 41 | func (u *surrealUniverse) getIndex(num surrealNumber) int { |
| 42 | // Since getIndex() is only ever called on 'num' which already exists in |
| 43 | // the universe, we return the result directly, without bothering to |
| 44 | // confirm an exact match. |
| 45 | // |
| 46 | // Also, we can get away with a direct comparison of these floating point |
| 47 | // numbers since there will be an exact match, guaranteed since 'num' is |
| 48 | // already in the universe. |
| 49 | return sort.Search(u.cardinality(), func(i int) bool {return u.numbers[i].value >= num.value}) |
| 50 | } |
| 51 | |
| 52 | func (u *surrealUniverse) cardinality() int { |
| 53 | return len(u.numbers) |
| 54 | } |
| 55 | |
| 56 | func (u *surrealUniverse) insert(num surrealNumber) { |
| 57 | // Before we can insert a number into the universe, we must first determine |
| 58 | // if it is newly discovered. We do this by looking at its ancestors, all |
| 59 | // guaranteed to be on the number line by construction, finding three |
| 60 | // cases: |
| 61 | // |
| 62 | // 1. There are zero ancestors. |
| 63 | // We have rediscovered 0 and can abort the insertion unless creating |
| 64 | // a brand new universe. |
| 65 | // |
| 66 | // 2. There is one ancestor. |
| 67 | // If the number extends the number line, it is new, otherwise it will |
| 68 | // be similar to a form with two ancestors and should be ignored since |
| 69 | // the two ancestor form is a better visual representation. |
| 70 | // |
| 71 | // 3. There are two ancestors. |
| 72 | // The number is only new if both ancestors are side-by-side on the |
| 73 | // number line. |
| 74 | |
| 75 | ancestorCount := num.leftSet.cardinality() + num.rightSet.cardinality() |
| 76 | switch ancestorCount { |
| 77 | case 0: |
| 78 | if u.cardinality() == 0 { |
| 79 | num.value = 0.0 |
| 80 | num.identifier = u.nextUniqueID |
| 81 | u.nextUniqueID++ |
| 82 | u.numbers = append(u.numbers, num) |
| 83 | } |
| 84 | case 1: |
| 85 | if num.leftSet.cardinality() == 1 { |
| 86 | index := u.getIndex(num.leftSet.members[0]) |
| 87 | if index+1 == u.cardinality() { |
| 88 | num.value = u.numbers[u.cardinality()-1].value + 1.0 |
| 89 | num.identifier = u.nextUniqueID |
| 90 | u.nextUniqueID++ |
| 91 | u.numbers = append(u.numbers, num) |
| 92 | } |
| 93 | } else { |
| 94 | index := u.getIndex(num.rightSet.members[0]) |
| 95 | if index == 0 { |
| 96 | num.value = u.numbers[0].value - 1.0 |
| 97 | num.identifier = u.nextUniqueID |
| 98 | u.nextUniqueID++ |
| 99 | u.numbers = append(u.numbers[:1], u.numbers...) |
| 100 | u.numbers[0] = num |
| 101 | } |
| 102 | } |
| 103 | case 2: |
| 104 | leftIndex := u.getIndex(num.leftSet.members[0]) |
| 105 | rightIndex := u.getIndex(num.rightSet.members[0]) |
| 106 | if leftIndex+1 == rightIndex { |
| 107 | num.value = (num.leftSet.members[0].value + num.rightSet.members[0].value) / 2 |
| 108 | num.identifier = u.nextUniqueID |
| 109 | u.nextUniqueID++ |
| 110 | u.numbers = append(u.numbers[:rightIndex+1], u.numbers[rightIndex:]...) |
| 111 | u.numbers[rightIndex] = num |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // ============================================================================= |
| 117 | |
| 118 | // Note: The following comparison functions apply only to numbers already in |
| 119 | // the universe, not to new numbers constructed from the universe. To |
| 120 | // determine where a (potentially) new number goes, first insert it into the |
| 121 | // universe. |
| 122 | |
| 123 | // This function implements Axiom 3 and is the root of all other comparisons. |
| 124 | func (u *surrealUniverse) isRelated(numA, numB surrealNumber) bool { |
| 125 | // By construction, no number in this program will ever have more than one |
| 126 | // element in its right or left sets, nor will those elements be of a form |
| 127 | // other than that 'registered' with the universe. That allows direct |
| 128 | // comparisons using the surrealNumber.identifier field via u.getIndex(). |
| 129 | |
| 130 | // --------------------------------- |
| 131 | |
| 132 | // First we implement the check "no member of the first number's left set |
| 133 | // is greater than or equal to the second number". |
| 134 | if numA.leftSet.cardinality() == 1 { |
| 135 | if u.getIndex(numA.leftSet.members[0]) >= u.getIndex(numB) { |
| 136 | return false |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // Now we implement the check "no member of the second number's right set |
| 141 | // is less than or equal to the first number". |
| 142 | if numB.rightSet.cardinality() == 1 { |
| 143 | if u.getIndex(numB.rightSet.members[0]) <= u.getIndex(numA) { |
| 144 | return false |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | return true |
| 149 | } |
| 150 | |
| 151 | func (u *surrealUniverse) isSimilar(numA, numB surrealNumber) bool { |
| 152 | if u.isRelated(numA, numB) && u.isRelated(numB, numA) { |
| 153 | return true |
| 154 | } |
| 155 | return false |
| 156 | } |
| 157 | |
| 158 | func (u *surrealUniverse) equal(left, right surrealNumber) bool { |
| 159 | return u.isSimilar(left, right) |
| 160 | } |
| 161 | |
| 162 | func (u *surrealUniverse) lessThanOrEqual(left, right surrealNumber) bool { |
| 163 | return u.isRelated(left, right) |
| 164 | } |
| 165 | |
| 166 | func (u *surrealUniverse) lessThan(left, right surrealNumber) bool { |
| 167 | return u.lessThanOrEqual(left, right) && !u.equal(left, right) |
| 168 | } |
| 169 | |
| 170 | func (u *surrealUniverse) greaterThanOrEqual(left, right surrealNumber) bool { |
| 171 | return !u.lessThan(left, right) |
| 172 | } |
| 173 | |
| 174 | func (u *surrealUniverse) greaterThan(left, right surrealNumber) bool { |
| 175 | return !u.isRelated(left, right) |
| 176 | } |
| 177 | |
| 178 | // ============================================================================= |
| 179 | |
| 180 | type surrealNumber struct { |
| 181 | leftSet surrealSet |
| 182 | rightSet surrealSet |
| 183 | value float64 |
| 184 | identifier uint |
| 185 | generation int |
| 186 | } |
| 187 | |
| 188 | type surrealSet struct { |
| 189 | members []surrealNumber |
| 190 | } |
| 191 | |
| 192 | func (s *surrealSet) isMember(num surrealNumber, u surrealUniverse) bool { |
| 193 | for i := 0; i < len(s.members); i++ { |
| 194 | if u.equal(num, s.members[i]) { |
| 195 | return true |
| 196 | } |
| 197 | } |
| 198 | return false |
| 199 | } |
| 200 | |
| 201 | func (s *surrealSet) cardinality() int { |
| 202 | return len(s.members) |
| 203 | } |
| 204 | |
| 205 | func (s *surrealSet) insert(num surrealNumber, u surrealUniverse) { |
| 206 | if !s.isMember(num, u) { |
| 207 | s.members = append(s.members, num) |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | func (s *surrealSet) remove(num surrealNumber, u surrealUniverse) { |
| 212 | for i := 0; i < len(s.members); i++ { |
| 213 | if u.equal(num, s.members[i]) { |
| 214 | s.members[i] = s.members[len(s.members)-1] |
| 215 | s.members = s.members[:len(s.members)-1] |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // ============================================================================= |
| 221 | |
| 222 | func main() { |
| 223 | // Flags to enable various performance profiling options. |
| 224 | cpuProfile := flag.String("cpuprofile", "", "Filename for saving CPU profile output.") |
| 225 | memProfilePrefix := flag.String("memprofileprefix", "", "Filename PREFIX for saving memory profile output.") |
| 226 | suppressOutput := flag.Bool("silent", false, "Suppress printing of numberline at end of simulation. Useful when profiling.") |
| 227 | |
| 228 | // Obtain termination conditions from user. |
| 229 | totalGenerations := flag.Int("generations", 2, "Number of generations of surreal numbers to breed.") |
| 230 | flag.Parse() |
| 231 | if *totalGenerations < 1 { |
| 232 | log.Fatal("ERROR: The argument to '-generations' must be greater than zero.") |
| 233 | } |
| 234 | remainingGenerations := *totalGenerations - 1 |
| 235 | |
| 236 | // Setup any CPU performance profiling requested by the user. This will run |
| 237 | // throughout program execution. |
| 238 | if *cpuProfile != "" { |
| 239 | cpuProFile, err := os.Create(*cpuProfile) |
| 240 | if err != nil { |
| 241 | log.Fatal("ERROR: Unable to open CPU profiling output file:", err) |
| 242 | } |
| 243 | pprof.StartCPUProfile(cpuProFile) |
| 244 | defer pprof.StopCPUProfile() |
| 245 | } |
| 246 | |
| 247 | // Build a universe to contain all the surreal numbers we breed. |
| 248 | // Seed it by hand with the number zero as generation-0. |
| 249 | var universe surrealUniverse |
| 250 | universe.nextUniqueID = 0 |
| 251 | fmt.Println("Seeding generation 0 by hand.") |
| 252 | universe.insert(surrealNumber{surrealSet{}, surrealSet{}, 0.0, 0, 0}) |
| 253 | |
| 254 | // Breed however many generations of numbers were requested by the user and |
| 255 | // add them all to the universe. |
| 256 | fmt.Printf("Breeding Generation:") |
| 257 | for generation := 1; generation <= remainingGenerations; generation++ { |
| 258 | // Give the user some idea of overall progress during long jobs. |
| 259 | if generation != 1 { |
| 260 | fmt.Printf(",") |
| 261 | } |
| 262 | fmt.Printf(" %d", generation) |
| 263 | |
| 264 | // First generate all possible reduced form symbols per Axiom 1. |
| 265 | potentialNumbers := permuteExistingNumbers(generation, universe) |
| 266 | // Now prune out any symbols which are NOT valid numbers per Axiom 2. |
| 267 | validNumbers := pruneInvalidNumbers(potentialNumbers, universe) |
| 268 | // Attempt to add the new numbers to the universe. Any duplicates will |
| 269 | // be weeded out in the attempt. |
| 270 | addNumbersToUniverse(validNumbers, &universe) |
| 271 | |
| 272 | // Setup any memory profiling requested by the user. This will snapshot |
| 273 | // the heap at the end of every generation. |
| 274 | if *memProfilePrefix != "" { |
| 275 | memProFile, err := os.Create(*memProfilePrefix + "-gen" + strconv.Itoa(generation) + ".mprof") |
| 276 | if err != nil { |
| 277 | log.Fatal("ERROR: Unable to write heap profile to disk:", err) |
| 278 | } |
| 279 | pprof.WriteHeapProfile(memProFile) |
| 280 | memProFile.Close() |
| 281 | } |
| 282 | } |
| 283 | fmt.Printf(".\n") |
| 284 | |
| 285 | |
| 286 | // Print the number line with generation on the horizontal axis and |
| 287 | // magnitude on the vertical axis. |
| 288 | if !(*suppressOutput) { |
| 289 | for i := 0; i < universe.cardinality(); i++ { |
| 290 | printlnNumber(universe.numbers[i]) |
| 291 | } |
| 292 | } |
| 293 | fmt.Println("After", *totalGenerations, "generations, the universe contains", len(universe.numbers), "numbers.") |
| 294 | fmt.Println("If output looks poor, ensure tabstop is eight spaces and that output doesn't wrap.") |
| 295 | } |
| 296 | |
| 297 | // ============================================================================= |
| 298 | |
| 299 | // We will only build permutations with 0 or 1 elements in each of the left and |
| 300 | // right sets. This covers all the reduced form permutations. Any longer |
| 301 | // permutations will be similar to one of the reduced forms. |
| 302 | func permuteExistingNumbers(generation int, universe surrealUniverse) []surrealNumber { |
| 303 | var numbers []surrealNumber |
| 304 | |
| 305 | // First build permutations with 1 element in each set. |
| 306 | for i := 0; i < universe.cardinality(); i++ { |
| 307 | for j := 0; j < universe.cardinality(); j++ { |
| 308 | var leftSet, rightSet surrealSet |
| 309 | leftSet.insert(universe.numbers[i], universe) |
| 310 | rightSet.insert(universe.numbers[j], universe) |
| 311 | newSurrealNumber := surrealNumber{leftSet,rightSet,0.0,0,generation} |
| 312 | numbers = append(numbers, newSurrealNumber) |
| 313 | } |
| 314 | } |
| 315 | // Now build permutations with one empty set and one 1-element set. |
| 316 | for i := 0; i < universe.cardinality(); i++ { |
| 317 | var tempSet surrealSet |
| 318 | tempSet.insert(universe.numbers[i], universe) |
| 319 | newSurrealNumber := surrealNumber{tempSet,surrealSet{},0.0,0,generation} |
| 320 | numbers = append(numbers, newSurrealNumber) |
| 321 | newSurrealNumber = surrealNumber{surrealSet{},tempSet,0.0,0,generation} |
| 322 | numbers = append(numbers, newSurrealNumber) |
| 323 | } |
| 324 | |
| 325 | return numbers |
| 326 | } |
| 327 | |
| 328 | func pruneInvalidNumbers(candidates []surrealNumber, universe surrealUniverse) []surrealNumber { |
| 329 | var numbers []surrealNumber |
| 330 | for i := 0; i < len(candidates); i++ { |
| 331 | if isValidSurrealNumber(candidates[i], universe) { |
| 332 | numbers = append(numbers, candidates[i]) |
| 333 | } |
| 334 | } |
| 335 | return numbers |
| 336 | } |
| 337 | |
| 338 | // Although a non-reduced-form number is technically valid, for the purposes of |
| 339 | // this program we're declaring it invalid. |
| 340 | func isValidSurrealNumber(candidate surrealNumber, universe surrealUniverse) bool { |
| 341 | // Is the number in reduced form? |
| 342 | if candidate.leftSet.cardinality() > 1 || candidate.rightSet.cardinality() > 1 { |
| 343 | return false |
| 344 | } |
| 345 | |
| 346 | // Is the number valid per Axiom 2? |
| 347 | if candidate.leftSet.cardinality() != 0 && candidate.rightSet.cardinality() != 0 { |
| 348 | for i := 0; i < candidate.leftSet.cardinality(); i++ { |
| 349 | for j := 0; j < candidate.leftSet.cardinality(); j++ { |
| 350 | // Since candidates are drawn from the universe, this comparison is allowed. |
| 351 | if universe.greaterThanOrEqual(candidate.leftSet.members[i], candidate.rightSet.members[j]) { |
| 352 | return false |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | return true |
| 359 | } |
| 360 | |
| 361 | func addNumbersToUniverse(numbers []surrealNumber, universe *surrealUniverse) { |
| 362 | for i := 0; i < len(numbers); i++ { |
| 363 | universe.insert(numbers[i]) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // Pretty print a number, indenting to indicate generation. |
| 368 | func printlnNumber(num surrealNumber) { |
| 369 | for i := 0; i < num.generation; i++ { |
| 370 | fmt.Printf(".\t\t") |
| 371 | } |
| 372 | fmt.Printf("%s = ", toBase26(num.identifier)) |
| 373 | fmt.Printf("<") |
| 374 | if num.leftSet.cardinality() == 0 { |
| 375 | fmt.Printf("---") |
| 376 | } else { |
| 377 | fmt.Printf("%s", toBase26(num.leftSet.members[0].identifier)) |
| 378 | } |
| 379 | fmt.Printf("|") |
| 380 | if num.rightSet.cardinality() == 0 { |
| 381 | fmt.Printf("---") |
| 382 | } else { |
| 383 | fmt.Printf("%s", toBase26(num.rightSet.members[0].identifier)) |
| 384 | } |
| 385 | fmt.Printf(">") |
| 386 | fmt.Printf("\n") |
| 387 | } |
| 388 | |
| 389 | // This function is a total hack, intended only to avoid printing identifiers |
| 390 | // as actual numbers since we don't want to imply any particular association to |
| 391 | // specific 'real' numbers yet. Instead, print them with [a-z] as base-26 |
| 392 | // integers. |
| 393 | func toBase26(num uint) (base26String []byte) { |
| 394 | // For alignment reasons, we never print more than three digits. Thus, any |
| 395 | // number greater than (26^3)-1 is out of range. |
| 396 | if num >= 26*26*26 { |
| 397 | base26String = []byte("xxx") |
| 398 | } else { |
| 399 | var firstByte, secondByte, thirdByte byte |
| 400 | thirdByte = byte((num % 26) + uint('a')); |
| 401 | num = num / 26; |
| 402 | secondByte = byte((num % 26) + uint('a')); |
| 403 | num = num / 26; |
| 404 | firstByte = byte((num % 26) + uint('a')); |
| 405 | num = num / 26; |
| 406 | base26String = append(base26String, firstByte) |
| 407 | base26String = append(base26String, secondByte) |
| 408 | base26String = append(base26String, thirdByte) |
| 409 | } |
| 410 | return base26String |
| 411 | } |