rlsmoc 1.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.5
2
+ Name: rlsmoc
3
+ Version: 1.0
4
+ Summary: Fast, highly-random latin squares generator
5
+ Author-email: Larry Trammell <ridgerat@ridgerat-tech.us>
6
+ Description-Content-Type: text/x-rst
7
+ License-Expression: CC-BY-4.0
8
+ License-File: LICENSE.txt
9
+ Import-Name: rlsmoc
10
+
11
+ ================================================
12
+ ABOUT THE RANDOM LATIN SQUARE GENERATOR MODULE
13
+ ================================================
14
+
15
+
16
+ Purpose
17
+ --------
18
+
19
+ The "rlsmoc.py" module implements the fastest known direct
20
+ generator method for constructing highly random Latin Squares.
21
+
22
+
23
+ What is a "Latin Square"?
24
+ -------------------------
25
+
26
+ For a given size parameter N, a Latin Square is a grid of
27
+ NxN cells, arranged in N rows and N columns, in which N
28
+ symbols are assigned to the cells in such a manner that each
29
+ symbol appears exactly once in every row and exactly once in
30
+ every column. The Random Latin Square generator uses the
31
+ numerical values 0 through N-1 as its symbol set, consistent
32
+ with indexing conventions of the Python language (and many
33
+ others).
34
+
35
+
36
+ What is a "Random Latin Square"?
37
+ --------------------------------
38
+
39
+ It should be clear that the rigid "Latin Constraint" rules
40
+ about "no symbol can appear twice in any row or in any
41
+ column" result in a layout that is very non-random. In the
42
+ context of Latin Squares, however, "randomness" refers to the
43
+ manner in which Latin Squares are selected ("generated").
44
+ If a generator algorithm produces Latin Square layouts such
45
+ that every possible Latin Square of the given size is equally
46
+ likely to be delivered, then the generator algorithm is
47
+ said to be "unbiased" and the set of Latin Squares produced
48
+ is said to be "random." Sets of Latin Squares that are not
49
+ truly random, but very difficult to distinguish from truly
50
+ random ones, are typically good enough for most practical
51
+ purposes.
52
+
53
+
54
+ How many Latin Squares are there?
55
+ ---------------------------------
56
+
57
+ Lots, a vast number, even in the cases when N is relatively
58
+ small. However, if you compare that number to the number of
59
+ possible ways that the same set of symbols could be randomly
60
+ placed into the square grid, the Latin Squares are a
61
+ miniscule subset.
62
+
63
+
64
+ How are random Latin Squares typically generated?
65
+ -------------------------------------------------
66
+
67
+ The traditional method-of-choice has been the Jacobson-Matthews
68
+ scrambler. To use this idea, you start with a Latin Square,
69
+ and apply a very large (but unspecified) number of randomized
70
+ scrambling "moves" to shuffle the symbols around the layout.
71
+ The starting Latin Square is typically a special nonrandom
72
+ case that is simple to compute. The scrambling approach
73
+ requires a relatively large amount of effort to sufficiently
74
+ break up patterns present in the starting layout. With enough
75
+ scrambling, the final results are biased only to a small
76
+ degree. The residual bias is almost undetectable for Latin
77
+ Squares of size 10x10 and larger.
78
+
79
+
80
+ What does this Random Latin Square generator do differently?
81
+ ------------------------------------------------------------
82
+
83
+ It is a direct method. It starts from an empty layout, and
84
+ attempts to place copies of every symbol as randomly as possible
85
+ without violating the "Latin Constraint" rules. After each
86
+ step, the number of empty cells is reduced by one. If it turns
87
+ out that some bad randomized assignment choices are made somewhere
88
+ in the process, a heuristic "conflict resolution" operation is
89
+ applied to remove the temporary impasse while introducing as
90
+ little bias as possible. A detectable bias remains for small
91
+ Latin Squares, but less than the residual bias produced by the
92
+ scrambling methods.
93
+
94
+
95
+ Does the Random Latin Square Generator have other strange properties?
96
+ ---------------------------------------------------------------------
97
+
98
+ Yes, but not necessarily bad. It tends to run about 3 times
99
+ faster than a good implementation of a scrambling algorithm.
100
+ It can generate Latin Squares for any size N=1 or greater
101
+ (even when it is not a smart idea). It can be implemented
102
+ in a manner that has guaranteed finite termination, unlike
103
+ the scramblers where you must make a judgment call about how
104
+ much mixing is "good enough." This implementation, however,
105
+ sacrifices some theoretical guarantees for the sake of faster
106
+ execution.
107
+
108
+
109
+ Does the implementation have unusual code dependencies?
110
+ -------------------------------------------------------
111
+
112
+ The random Latin Square generator uses the numpy module for its
113
+ highly-structured array types with efficient indexing. Approximately
114
+ 5 x N-squared storage locations are used for the Latin Square
115
+ storage and internal indexing work areas. The "short" integer data
116
+ type is used to keep data storage compact. This constrains the
117
+ size of the Latin Squares to N < 32768, but this is very unlikely
118
+ to be a practical limitation. Features of the numpy random number
119
+ generator are used for making randomized choices.
120
+
121
+
122
+ Where can I find more information about the algorithm?
123
+ ------------------------------------------------------
124
+
125
+ Glad you are interested. A detailed explanation is provided in
126
+ the rlsmoc.epub ("Random Least Squares by the Method of Covers")
127
+ document provided with this module. It is tedious, but intended
128
+ to be understandable. Don't be intimidated.
129
+
130
+
131
+ Is the method published in the refereed journals?
132
+ -------------------------------------------------
133
+
134
+ No. It has generated a remarkable lack of interest from the
135
+ academic community. Strange, because as the great Nikolai Lobachevsky
136
+ once observed, the only thing that really matters is who publishes
137
+ first. And this "unpublished" method is low-hanging fruit that
138
+ anyone hungry to publish could easily exploit.
139
+
140
+
141
+ Why is this implementation considered "experimental?"
142
+ -----------------------------------------------------
143
+
144
+ Not because it doesn't work, or isn't reliable... There
145
+ are two main reasons. One, it is coded for clarity of
146
+ presentation rather than optimality for any particular purpose:
147
+ security, robustness to user error, ease of application,
148
+ etc.. Two, it does not have the years of field application
149
+ experience that you would want for a thoroughly trusted method.
150
+ It is expected that you will adapt/constrain/improve/test
151
+ the coding thoroughly before applying it. Various "optimizations"
152
+ for specific purposes are left to you.
153
+
154
+
155
+ How do I use the Random Latin Square generator?
156
+ -----------------------------------------------
157
+
158
+ Easy. Import the module. Instantiate a Latin Square object
159
+ of the desired size, which reserves storage. Apply the "fill"
160
+ method to populate the Latin Square with the symbol assignments.
161
+ Apply the "fill" method again to repopulate the Latin Square
162
+ storage with new and different symbol assignments. See the
163
+ "example.py" code file.
164
+
165
+
166
+ How do I access the results?
167
+ ----------------------------
168
+
169
+ One of the arrays within the Random Latin Square object is a
170
+ two dimensional array called "store" that you can access. The
171
+ standard Python/numpy modules provide a simple "print" command
172
+ that works fine for displaying small Latin Square results
173
+ from that storage. For larger Latin Squares, you will probably
174
+ need to develop some alternate storage and presentation methods,
175
+ for example, copy the results into a file or database. Keep in
176
+ mind that you can use the row indices, column indices, and grid
177
+ contents as index numbers. For example, you could use the row
178
+ index to access a list of "laboratory names", the column index
179
+ to access a list of "test dates", and the cell contents to index
180
+ a list of "trial codes," to organize and display a Latin Square
181
+ design for a pharmaceutical safety test based on a Latin Square
182
+ experiment design.
183
+
184
+
185
+ Are there any other obscure details?
186
+ ------------------------------------
187
+
188
+ Just one. Some remedial operations (somewhat reminiscent of
189
+ scrambling operations used by other methods but on a greatly
190
+ reduced scale) are applied by default to reduce bias. This
191
+ has a measurable and perhaps relevant effect on small Latin
192
+ Squares, but it is pointless for moderate to large Latin
193
+ Squares. You can configure the generator to omit the
194
+ bias-adjustment operations, and gain a little efficiency, by
195
+ specifying the optional named parameter "comp=0" when the Latin
196
+ Square generator object is instantiated.
197
+
198
+
@@ -0,0 +1,5 @@
1
+ rlsmoc.py,sha256=qJuCdRt7oJD2293zvDxS4CNuM-D8RoCqj4mhdCA9mmg,19942
2
+ rlsmoc-1.0.dist-info/licenses/LICENSE.txt,sha256=hdOuoCHMhfzNWosMSRsLznT2P2Fs0D1eJg2bQjGPFBw,616
3
+ rlsmoc-1.0.dist-info/WHEEL,sha256=uUFU-y0rXo06J7bdNhb3Yy33H9ThPPd2viUqkqnCjeI,99
4
+ rlsmoc-1.0.dist-info/METADATA,sha256=Iz4hOkBODg7fvc44a3ikTcCXOnpirHOVMNrwwt4YYyQ,8261
5
+ rlsmoc-1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: flit 4.2.0
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
@@ -0,0 +1,20 @@
1
+
2
+
3
+ License-File: LICENSE.txt
4
+ License-Expression: CC-BY-4.0
5
+
6
+ ===========================================================================
7
+
8
+ All items in this distribution are released under the CC-BY-4 International
9
+ license.
10
+
11
+ In general terms, that means that you are allowed to use, adapt,
12
+ and distribute copies of these items without royalty or permission
13
+ restrictions. However, if you derive and distribute modified
14
+ versions, you are required to cite appropriate credit to the author
15
+ in your redistribution.
16
+
17
+ The exact terms of the license are available at
18
+ https://www.creativecommons.org/licenses/by/4.0/
19
+
20
+
rlsmoc.py ADDED
@@ -0,0 +1,571 @@
1
+ """ Fast, highly-random latin squares generator """
2
+ __version__ = "1.0"
3
+
4
+
5
+ """
6
+ This module provides an implementation of the fast Method of Covers
7
+ algorithm for pseudo-randomly constructing Latin Squares.
8
+
9
+ SPDX-License-Identifier: CC-BY-4.0
10
+ This code is provided June 4, 2026 by its author Larry Trammell under the
11
+ CC-BY license; generally, that means you can do pretty much anything you want
12
+ with this as long as you cite credit when appropriate, and don't try to claim
13
+ total ownership for yourself.
14
+
15
+ For license details see:
16
+ https://creativecommons.org/licenses/by/4.0/
17
+
18
+ See the application example at the end of this file.
19
+
20
+ -----------
21
+
22
+ This is a class to provide data structures used by the Method of Covers
23
+ as it randomly generates Latin Squares.
24
+
25
+ An "availability list" maintains an unordered list of items that are "taken"
26
+ and a list of items that are "available." Since every item is either taken
27
+ or not, the two lists are packed unordered into a single fixed-length array
28
+ that is partitioned into two sections. The "availability list" facilitates
29
+ operations like "test all unoccupied cells in the row."
30
+
31
+ A "cross-indexing list" reports the postion in the list where a specified
32
+ item is stored. This facilitates operations like "find the location
33
+ in the column where the symbol 2 is stored."
34
+
35
+ """
36
+
37
+ # Use the numpy library to define "short integer" data type.
38
+ import numpy as np # numeric data types
39
+
40
+ # Copy utility
41
+ from copy import deepcopy
42
+
43
+ # Random variate generation
44
+ from numpy.random import Generator, PCG64
45
+ #from numpy.random import Generator, MT19937
46
+ rg = Generator( PCG64() )
47
+
48
+ # A utility function to select a discrete number 0 <= val < lim, uniformly
49
+ # and randomly.
50
+ #
51
+ def randix( lim ) :
52
+ val = rg.choice(lim, shuffle=False)
53
+ return val
54
+
55
+
56
+ # ========================================================================
57
+ #
58
+ # The "split list" utility class
59
+ #
60
+ # ========================================================================
61
+
62
+ class splitlist :
63
+ 'A class that maintains cross-reference and selection information'
64
+
65
+ # The constructor method reserves storage and size information.
66
+ #
67
+ def __init__(self, Nrc) :
68
+ # Administrative parameters and special flags
69
+ self.len = Nrc # size of storage lists
70
+ self.short0 = np.short(0) # count initializer
71
+ self.empty = np.short(-1) # flag to indicate "unused location"
72
+ # Number of assigned cells in each xtaken list
73
+ self.Ntaken = np.ndarray((Nrc), dtype=np.short)
74
+ # Availability list
75
+ self.xavail = np.ndarray((Nrc,Nrc), dtype=np.short)
76
+ # Selection cross reference list
77
+ self.xsort = np.ndarray((Nrc,Nrc), dtype=np.short)
78
+ # Content cross reference list
79
+ self.xref = np.ndarray((Nrc,Nrc), dtype=np.short)
80
+ self.clear()
81
+
82
+
83
+ # An initializer. It sets all cross-reference entries to "empty," all
84
+ # "taken" counts to 0.
85
+ #
86
+ def clear(self) :
87
+ # No symbols have been taken; that means all locations are available
88
+ self.Ntaken.fill(self.short0)
89
+ # All items are initially present in the "available" section
90
+ for sublist in range(self.len) :
91
+ for ix in range(self.len) :
92
+ self.xavail[sublist,ix] = ix
93
+ # No locations are swapped in selection cross reference
94
+ self.xsort = deepcopy(self.xavail)
95
+ # No contents are noted by content cross references
96
+ self.xref.fill(self.empty)
97
+
98
+
99
+ # Swap the contents of two locations in the availability array.
100
+ # This is typically used internally to shift an item between the
101
+ # "available" and "taken" sections of the availability list.
102
+ # Content cross-references are not changed.
103
+ #
104
+ def swap ( self, sublist, item1, item2 ) :
105
+
106
+ # Extract the elements currently stored at the given locations
107
+ elem1 = self.xavail[sublist,item1]
108
+ elem2 = self.xavail[sublist,item2]
109
+
110
+ # Swap these items in availability storage
111
+ self.xavail[sublist,item1] = elem2
112
+ self.xavail[sublist,item2] = elem1
113
+
114
+ # Swap these items in the selection cross reference
115
+ self.xsort[sublist,elem2] = item1
116
+ self.xsort[sublist,elem1] = item2
117
+
118
+
119
+ # Move an item from the "available" section to the "taken" section
120
+ # of the selection array. Update the cross references.
121
+ #
122
+ def assign ( self, sublist, item, value ) :
123
+ # Cross reference the content of the new item
124
+ self.xref[sublist,value] = item
125
+ # Locate the split between "taken" and "available" items
126
+ lastix = self.Ntaken[sublist]
127
+ # Determine location of the element in availability list
128
+ ix = self.xsort[sublist,item]
129
+ # Swap locations if necessary to move item into taken section
130
+ if ix != lastix :
131
+ self.swap( sublist, lastix, ix )
132
+ # Relocate the partition between taken and available
133
+ self.Ntaken[sublist] = lastix+1
134
+
135
+
136
+ # Release an item from the "taken" section back into the
137
+ # "available" section. Update cross references.
138
+ #
139
+ def release ( self, sublist, item, value ) :
140
+ # Remove the cross reference to the content value
141
+ self.xref[sublist,value] = self.empty
142
+ # Locate end of the "taken" items section of the sorting array
143
+ lastix = self.Ntaken[sublist] - 1
144
+ # Locate the item to be released within availability list
145
+ ix = self.xsort[sublist,item]
146
+ # If the two locations are not the same, swap them
147
+ if ix != lastix :
148
+ self.swap( sublist, lastix, ix )
149
+ # Relocate the partition between taken and available
150
+ self.Ntaken[sublist] = lastix
151
+
152
+
153
+ # Use the content cross reference to test whether specified content
154
+ # is already present in the "taken" section of the availability list.
155
+ # Reports location index if the value is present, or "empty" otherwise.
156
+ #
157
+ def val_location ( self, sublist, value ) :
158
+ # Test whether value is listed in the content cross-ref
159
+ indx = self.xref[sublist, value]
160
+ return indx
161
+
162
+
163
+ # Randomly select an item from the available item section, without
164
+ # changing status. If optional argument 'lim' is specified, limit
165
+ # the search to this number of available cells; otherwise, any available
166
+ # cell is eligible for selection. If no such cell is available,
167
+ # return an "empty" flag; otherwise, return the contents of the
168
+ # selected cell. A side effect is a partial shuffling of locations
169
+ # within the sorted lists.
170
+ #
171
+ def select_avail ( self, sublist, lim=None ) :
172
+ # If no range limit is specified, allow any available location
173
+ av = self.len - self.Ntaken[sublist]
174
+ if lim != None :
175
+ if lim <= av :
176
+ av = lim
177
+
178
+ # Range of locations eligible for selection
179
+ avstart = self.Ntaken[sublist]
180
+ avlast = avstart + av - 1
181
+
182
+ # Special cases when no random sampling is required to extract item
183
+ if av == 0 :
184
+ return None
185
+
186
+ if av == 1 :
187
+ item = self.xavail[sublist,avstart]
188
+ return item
189
+
190
+ # Pick any eligible list location at random
191
+ slot = randix(av)+avstart
192
+
193
+ # Swap this item to the last selectable location so that it is
194
+ # possible to skip it during follow-up searches.
195
+ if slot != avlast :
196
+ self.swap( sublist, slot, avlast )
197
+ item = self.xavail[sublist,avlast]
198
+ return item
199
+
200
+
201
+ # Randomly select an item from the "taken" item section, without
202
+ # changing status. If optional argument 'lim' is specified, limit
203
+ # the search to this number of occupied cells; otherwise, any
204
+ # occupied cell is eligible for selection. If no occupied cell is
205
+ # present, return an "empty" flag; otherwise, return the contents of
206
+ # the selected cell. A side effect is a partial shuffling of locations
207
+ # within the ordered cell lists.
208
+ #
209
+ def select_taken ( self, sublist, lim=None ) :
210
+ # If no range limit is specified, allow any occupied location
211
+ av = self.Ntaken[sublist]
212
+ if lim != None :
213
+ if lim < av :
214
+ av = lim
215
+
216
+ # Range of locations eligible to search
217
+ avstart = 0
218
+ avlast = av - 1
219
+
220
+ # Special cases when no random sampling is required to extract item
221
+ if av == 0 :
222
+ return None
223
+
224
+ if av == 1 :
225
+ item = self.xavail[sublist,0]
226
+ return item
227
+
228
+ # Pick any eligible list item at random
229
+ slot = randix(av)
230
+ if slot != avlast :
231
+ self.swap( sublist, slot, avlast )
232
+ item = self.xavail[sublist,avlast]
233
+ return item
234
+
235
+ # End of rlat_splitlist class definition
236
+
237
+
238
+ # ========================================================================
239
+ #
240
+ # The Method of Covers
241
+ #
242
+ # ========================================================================
243
+
244
+ # The Latin Square class, including the methods to populate it.
245
+ #
246
+ class rlatin :
247
+ 'Defines a class that constructs a pseudo-random Latin square'
248
+
249
+ # The constructor method reserves storage and size information.
250
+ def __init__(self, Nrc, comp=2) :
251
+ # Configuration parameters
252
+ self.Nrc = Nrc
253
+ if comp >= 0 :
254
+ self.comp = comp
255
+
256
+ # "Flag" constant for identifying incomplete content
257
+ self.empty = np.short(-1)
258
+
259
+ # Storage for the constructed Latin Square
260
+ self.store = np.ndarray((Nrc,Nrc), dtype=np.short)
261
+
262
+ # A cross-reference structure for assignments into rows
263
+ self.rowxref = splitlist( Nrc )
264
+
265
+ # A cross-reference structure for assignments into columns
266
+ self.colxref = splitlist( Nrc )
267
+
268
+ # Initialize storage optional
269
+ # self.clear( )
270
+
271
+
272
+ # Set all internal storage values to the initial state.
273
+ #
274
+ def clear( self ) :
275
+ self.store.fill( self.empty )
276
+ self.rowxref.clear()
277
+ self.colxref.clear()
278
+
279
+
280
+ # Attempt to randomly select an empty cell in the specified row such
281
+ # that there is no conflict with symbol 'sym' in that column. If
282
+ # found, return the column index of the available cell. Otherwise,
283
+ # return an "empty" result.
284
+ #
285
+ def select_feasible_cell( self, row, sym ) :
286
+ # How many empty cells are there in the row?
287
+ lim = self.Nrc - self.rowxref.Ntaken[row]
288
+
289
+ # Randomly check the open cells listed for this row
290
+ while lim > 0 :
291
+ col = self.rowxref.select_avail( row, lim )
292
+ # Is there no conflict in this column?
293
+ test = self.colxref.xref[col,sym]
294
+ if test == self.empty :
295
+ return col
296
+ lim -= 1
297
+ # Conflict... try another column
298
+
299
+ # We failed to find a suitable cell. Report the failure.
300
+ return self.empty
301
+
302
+
303
+ # Resolve the symbol assignment conflict that is discovered in the
304
+ # row when trying to find a location where 'sym' can be stored.
305
+ # One of the three heuristics will succeed. There is no return value.
306
+ #
307
+ def Resolve( self, row, sym ) :
308
+
309
+ # Apply the split-symbol heuristic
310
+ col = self.Resolve_by_split( row, sym )
311
+ if col != self.empty :
312
+ return
313
+
314
+ # Apply the general cycle-tracing heuristic.
315
+ # This always works, but has a potential to cause bias.
316
+ self.Resolve_by_tracing( row, sym )
317
+
318
+
319
+
320
+
321
+ # Apply the split-symbol resolution strategy to the current row.
322
+ # This heuristic attempts to move the 'current symbol C' out of a
323
+ # column where it blocks assignments in the current row, into
324
+ # a different column position where there is no conflict. Thus
325
+ # the pattern - C becomes C -
326
+ # D - D -
327
+ # and a copy of current symbol C can now be placed diagonally to
328
+ # the other without conflict to form the pattern
329
+ # C -
330
+ # D C
331
+ # If this succeeds, return the index of the column where the
332
+ # symbol assignment was successful. Otherwise, report an 'empty'
333
+ # flag to indicate failure.
334
+ #
335
+ def Resolve_by_split( self, row, sym ) :
336
+
337
+ # All empty cells in row are initiallly eligible for testing
338
+ lim = self.Nrc - self.rowxref.Ntaken[row]
339
+
340
+ # Test row locations where the cell is empty
341
+ while lim > 0 :
342
+ col = self.rowxref.select_avail( row, lim )
343
+
344
+ # See whether this column already has the current symbol present
345
+ rowx = self.colxref.xref[col,sym]
346
+ if rowx == self.empty :
347
+ # Not present, try another column.
348
+ lim = lim-1
349
+ continue
350
+
351
+ # We found the current symbol in the column. Test the empty
352
+ # cells in that row for feasibility.
353
+ limx = self.Nrc - self.rowxref.Ntaken[rowx]
354
+ while limx > 0 :
355
+ colx = self.rowxref.select_avail( rowx, limx )
356
+ if self.colxref.val_location( colx, sym ) == self.empty :
357
+
358
+ # No conflict at this location. Perform the split operation.
359
+ self.rowxref.release( rowx, col, sym )
360
+ self.colxref.release( col, rowx, sym )
361
+ self.store[rowx,col] = self.empty
362
+
363
+ self.rowxref.assign( row, col, sym )
364
+ self.colxref.assign( col, row, sym )
365
+ self.store[row,col] = sym
366
+
367
+ self.rowxref.assign( rowx, colx, sym )
368
+ self.colxref.assign( colx, rowx, sym )
369
+ self.store[rowx,colx] = sym
370
+
371
+ # Indicate success
372
+ return col
373
+
374
+ # No, column already has the symbol. Try another.
375
+ limx = limx-1
376
+
377
+ # We couldn't apply the split heuristic here. Try another
378
+ # empty slot from the current row.
379
+ lim = lim-1
380
+
381
+ # If we fall through both loops, report failure.
382
+ return self.empty
383
+
384
+
385
+ # Resolve the conflict in the current row using the general tracing
386
+ # method. This always works, but also causes the most bias damage.
387
+ #
388
+ def Resolve_by_tracing( self, row, sym ) :
389
+
390
+ # This is a dummy placeholder symbol
391
+ dummy = self.Nrc-1
392
+
393
+ col = self.rowxref.select_avail( row )
394
+ # Loop invariant:
395
+ # row,col point to an empty cell where conflict might exist.
396
+ while( True ) :
397
+ # Check whether sym is already present somewhere in column
398
+ rowx = self.colxref.xref[col,sym]
399
+
400
+ # Check whether resolution has been reached
401
+ if rowx == self.empty :
402
+ # Resolved... Assign symbol and finish.
403
+ self.rowxref.assign( row, col, sym )
404
+ self.colxref.assign( col, row, sym )
405
+ self.store[ row,col ] = sym
406
+ break
407
+
408
+ # Conflict is present in column. Remove conflicting symbol.
409
+ # Replace it with temporary dummy.
410
+ self.rowxref.release( rowx, col, sym )
411
+ self.colxref.release( col, rowx, sym )
412
+ self.store[ rowx,col ] = self.empty
413
+
414
+ # Temporily block backtracking by replacing with dummy symbol
415
+ self.rowxref.assign( rowx, col, dummy )
416
+ self.colxref.assign( col, rowx, dummy )
417
+ self.store[ rowx,col ] = dummy
418
+
419
+ # Store the current symbol at the previous trace location
420
+ self.rowxref.assign( row, col, sym )
421
+ self.colxref.assign( col, row, sym )
422
+ self.store[ row,col ] = sym
423
+
424
+ # Select an empty row cell at random in conflict row
425
+ colx = self.rowxref.select_avail( rowx )
426
+
427
+ # Remove the temporary dummy symbol
428
+ self.rowxref.release( rowx, col, dummy )
429
+ self.colxref.release( col, rowx, dummy )
430
+ self.store[ rowx,col ] = self.empty
431
+
432
+ # Advance to the next trace location
433
+ row = rowx
434
+ col = colx
435
+
436
+ # We must depend on the algorithm correctness to guarantee
437
+ # that this loop terminates.
438
+
439
+
440
+ # Having just completed a cover for symbol sym1, pick a second
441
+ # symbol sym2 randomly, and use the symbol pair to define a
442
+ # circuit within the Latin Square layout. Trace this circuit,
443
+ # And after visiting each cell, toggle the symbol content from
444
+ # sym1 to sym2 or from sym2 to sym1.
445
+ #
446
+ def Toggle( self, sym1 ) :
447
+
448
+ # Pick a second symbol from those used for previous covers
449
+ if sym1 == 0 :
450
+ return
451
+ if sym1 == 1 :
452
+ sym2 = 0
453
+ else :
454
+ sym2 = randix( sym1 )
455
+
456
+ # Pick any start row randomly
457
+ rowst = randix( self.Nrc )
458
+
459
+ # Find start column where sym1 is present in this row
460
+ colst = self.rowxref.xref[rowst,sym1]
461
+
462
+ # Current position is the start cell location
463
+ row = rowst
464
+ col = colst
465
+
466
+ # Clear the start cell
467
+ self.rowxref.release( row, col, sym1 )
468
+ self.colxref.release( col, row, sym1 )
469
+ self.store[ row,col ] = self.empty
470
+
471
+ # Find sym2 within the current column
472
+ rowx = self.colxref.xref[col,sym2]
473
+
474
+ # Clear sym2 from the new cell
475
+ self.rowxref.release( rowx, col, sym2 )
476
+ self.colxref.release( col, rowx, sym2 )
477
+ self.store[ rowx,col ] = self.empty
478
+ row = rowx
479
+
480
+ # Trace along circuit partition using selected symbols
481
+ while( True ) :
482
+ # Find sym1 within the current row
483
+ colx = self.rowxref.xref[row,sym1]
484
+
485
+ # Clear sym1 from the new cell
486
+ self.rowxref.release( row, colx, sym1 )
487
+ self.colxref.release( colx, row, sym1 )
488
+ self.store[ row,colx ] = self.empty
489
+
490
+ # Store sym1 back in the previous cell
491
+ self.rowxref.assign( row, col, sym1 )
492
+ self.colxref.assign( col, row, sym1 )
493
+ self.store[ row,col ] = sym1
494
+
495
+ # Advance to the column to the newest cell
496
+ col = colx
497
+
498
+ # Find the next sym2 in the new column.
499
+ rowx = self.colxref.xref[col,sym2]
500
+
501
+ # Clear sym1 from the new cell
502
+ self.rowxref.release( rowx, col, sym2 )
503
+ self.colxref.release( col, rowx, sym2 )
504
+ self.store[ rowx,col ] = self.empty
505
+
506
+ # Toggle the contents of the previous cell.
507
+ self.rowxref.assign( row, col, sym2 )
508
+ self.colxref.assign( col, row, sym2 )
509
+ self.store[ row,col ] = sym2
510
+
511
+ # Have we reached the start row?
512
+ if rowx == rowst :
513
+ # Replace contents of the final cells
514
+ self.rowxref.assign( rowst, col, sym1 )
515
+ self.colxref.assign( col, rowx, sym1 )
516
+ self.store[ rowx,col ] = sym1
517
+ self.rowxref.assign( rowst, colst, sym2 )
518
+ self.colxref.assign( colst, rowst, sym2 )
519
+ self.store[ rowst,colst ] = sym2
520
+ return
521
+
522
+ # Advance to the newest cell location.
523
+ row = rowx
524
+
525
+ # The trace always terminates when it reaches the initial
526
+ # cell again.
527
+ pass
528
+
529
+
530
+ # Populate the contents of the Latin Square reserved storage with new
531
+ # randomly-selected Latin Square contents. Do this by constructing
532
+ # covers for unassigned storage cells, one cover at a time, each
533
+ # cover determining one symbol assignment for every row.
534
+ #
535
+ def fill( self ):
536
+ # Initialize all storage elements
537
+ self.clear( )
538
+
539
+ # Build a cover for each symbol value
540
+ for sym in range(self.Nrc) :
541
+
542
+ # Find a symbol assignment location for each row
543
+ for row in range(self.Nrc) :
544
+ col = self.select_feasible_cell( row, sym )
545
+ if col != self.empty :
546
+ # Store the symbol and cross reference position
547
+ self.store[row,col] = sym
548
+ self.rowxref.assign( row, col, sym )
549
+ self.colxref.assign( col, row, sym )
550
+ else :
551
+ # Use conflict resolution to assign the symbol
552
+ self.Resolve( row, sym )
553
+ pass
554
+
555
+ # Perform a scrambling trace to counter bias
556
+ for reps in range(self.comp) :
557
+ self.Toggle( sym )
558
+
559
+ # End of rlsmoc.py class definition
560
+
561
+
562
+ """
563
+ Test program, using default bias compensation.
564
+ Copy to a separate python file, remove comment marks, and run it.
565
+ """
566
+ #import rlsmoc as rls
567
+ #Nsize = 7
568
+ #rl = rls.rlatin(Nsize)
569
+ #rl.fill()
570
+ #print(rl.store)
571
+