SBR.py 6.86 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""
Interface for a Reversal Class.
"""


# Returns the cost of the given reversal
def rev_cost(reversal):
    return abs(reversal.beg - reversal.end) + 2  # Currently omits the 1/3 factor


class Reversal:
    def __init__(self, i, j, time=0):
        if i > j:
            raise ValueError('Reversal\'s left index greater than right index')
        self.beg = i
        self.end = j
        if time != 0:
            self.time_remaining = time
        else:
            self.time_remaining = rev_cost(self)


    # Decrease the time remaining for the reversal by the given time (does not fall below zero)
    # Returns the subsequent time remaining
    def dec_time(self, t):
        self.time_remaining = max(0, self.time_remaining - t)
        return self.time_remaining

    def get_time_remaining(self):
        return self.time_remaining

    def get_length(self):
        return abs(self.beg - self.end) + 1

    def __lt__(self, other):
        return self.beg < other.beg

38
    def __repr__(self):
39
40
        return "(" + str(self.beg) + ", " + str(self.end) + ")"

41
42
43
    def __str__(self):
        return repr(self)

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

# Perform the given reversal on the given permutation
def reverse(permutation, reversal):
    i = reversal.beg
    j = reversal.end
    permutation[i:j+1] = permutation[i:j+1][::-1]


# Determines if the reversals in the given list are independent, where perm_length is the length of the permutation
def independent(rev_list, perm_length):
    busy = [0]*perm_length
    for rev in rev_list:
        for i in range(rev.beg, rev.end+1):
            if busy[i]:
                return False
            busy[i] = 1
    return True


# Simpler function that checks if rev is independent to all reversals in the
# active rev list, when we know that the latter are already all indepdendent
def check_independent(rev, active_rev_list):
    for a_rev in active_rev_list:
        if not (rev.beg > a_rev.end or rev.end < a_rev.beg):
            return False
    return True


# Checks whether the item at index i is busy; namely, if i is participating in
# a reversal in the rev_list
def is_busy(rev_list, i):
    for rev in rev_list:
        if rev.beg <= i and rev.end >= i:
            return True
    return False


# Determines if the permutation is sorted (i.e. if it is the identity permutation from start to end, inclusive)
def is_sorted(permutation, start, end):
    return permutation == list(range(start, end+1))


# Determines if the permutation is a valid permutation on the elements from start to end, inclusive
def is_valid_permutation(permutation, start, end):
    return sorted(permutation) == list(range(start,end+1))


# Determines the time (in time steps) taken to perform the reversals in the given list in the given order in parallel
def compress_reversals(revlist, permsize):
    timesteps = []
    for rev in revlist:
        init_step = len(timesteps)
        for step in timesteps[::-1]:
            busy = False
            for i in range(rev.beg, rev.end+1):
                if step[i]:
                    busy = True
                    break
            if busy:
                break
            init_step -= 1
        while init_step + rev_cost(rev) - 1 > len(timesteps) - 1:
            timesteps.append([0]*permsize)
Hrishee Shastri's avatar
Hrishee Shastri committed
107
    
108
109
110
        for i in range(init_step, init_step + rev_cost(rev)):
            for j in range(rev.beg, rev.end+1):
                timesteps[i][j] = 1
Hrishee Shastri's avatar
Hrishee Shastri committed
111

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    return len(timesteps) 


class ReversalCompresser:
    """
    Alternate implementation of the compress_reversals function. 
    """
    def __init__(self):
        """
        List to be sorted
        """
        self.model = []
        self.active_revs = []
        self.counter = 0

    def reset(self):
        self.__init__()

    def is_busy(self, start_index, end_index):
        """
        checks if chain is busy between start index and end index, inclusive
        """
        return 1 in self.model[start_index:end_index+1]

    def make_busy(self, start_index, end_index):
        """inclusive"""
        for i in range(start_index, end_index + 1):
            self.model[i] = 1

    def make_free(self, start_index, end_index):
        for i in range(start_index, end_index + 1):
            self.model[i] = 0

    def independent(self, rev, revlist):
        """
        checks if rev is independent of all reversals in revlist, when we allow None in revlist
        """
        for a_rev in revlist:
            if a_rev is None:
                continue
            if not (rev.beg > a_rev.end or rev.end < a_rev.beg):
                return False
        return True

    def update(self):
        for rev in self.active_revs:
            rev.step -= 1
            if rev.step == 0:
                self.make_free(rev.beg, rev.end)
        self.active_revs = [rev for rev in self.active_revs if rev.step > 0]
        self.counter += 1 


    def compress(self, revlist, permsize):
        revlist = revlist[:]
        self.reset()
        self.model = [0]*permsize 
        self.active_revs = []

        while len(revlist) > 0:
            for r in range(len(revlist)):
                rev = revlist[r]
                if not self.is_busy(rev.beg, rev.end) and self.independent(rev, revlist[:r]):
                    self.make_busy(rev.beg, rev.end)
                    self.active_revs.append(rev)
                    rev.step = rev.get_length() + 1 # to account for the + 1 in the cost fucntion
                    revlist[r] = None 
            revlist = list(filter(lambda i : i is not None, revlist))
            self.update()

        # wait for final reversals to finish, if there are any 
        while self.active_revs != []:
            self.update()

        return self.counter 



def odd_even_sort(L):
    """
    L: List to be sorted. Since we can reduce the problem of sorting according to a permutation 
    pi to just sorting according to the identity permutation, we just sort normally.

    Odd even sort is performed in parallel. Each pass is an odd pass or even pass, where we look
    at every odd/even pair and swap if they are out of order. Each pass takes time 1, since there are
    n/2 swaps per pass (each taking time 1) done in parallel.


    sorts in place. Returns the cost 
    """
    cost = 0
    sortflag = False
    addflag = False

    while not sortflag:
        sortflag = True
        addflag = False

        for i in range(1, len(L) - 1, 2):
            if L[i] > L[i+1]:
                L[i], L[i+1] = L[i+1], L[i]
                sortflag = False
                addflag = True

        cost += int(addflag)
        addflag = False

        for i in range(0, len(L) - 1, 2):
            if L[i] > L[i+1]:
                L[i], L[i+1] = L[i+1], L[i]
                sortflag = False
                addflag = True

        cost += int(addflag)

    return cost



def apply_revs(revs, perm):
    """
    Applies reversals in list revs in order to permutation perm, in place
    """
    for rev in revs:
        reverse(perm, rev)