def run(self, lb, ub): self.PzSeq = [] self.PzPrimes = [] self.nPzPrimes = [] self.numSeq = [] self.tpSeq = [] self.lBound = lb self.uBound = ub self.size = self.uBound - self.lBound for i in range(self.lBound, self.uBound): PzTmp = self.Pz(i) self.PzSeq.append((fract(PzTmp).limit_denominator(), fract(1 - PzTmp).limit_denominator())) for (Pz, nPz) in self.PzSeq: if self.verbosity > 0: print '--------------------' if self.verbosity > 0: print '{0}, {1}'.format(Pz, nPz) # check if numerator prime if self.isPrime(Pz.numerator): self.PzPrimes.append(Pz.numerator) self.numSeq.append(Pz.numerator) if self.isPrime(nPz.numerator): self.nPzPrimes.append(nPz.numerator) self.numSeq.append(nPz.numerator) if self.verbosity > 0: print '--------------------' self.tpSeq = self.findTwins(self.numSeq) print '--------------------' print self.numSeq print '--------------------' return { 'PzPrimes': self.PzPrimes, 'nPzPrimes': self.nPzPrimes, 'numSeq': self.numSeq }
def _init_base(self): self.rows = self.origrows[:] for i, row in enumerate(self.rows): if not row: continue self.rows[i] = row[:] self.m = len(self.rows)-1 #excluding objective row self.b = [v[0] for v in self.rows if v] #initial b nvars = len(self.vars) self.base = list(range(nvars-self.m-1, nvars)) self.base[0] = 0 #reserved for the objective row self.cols = nvars #0 for RHS for vi in range(nvars-self.m, nvars): if self.vars[vi][0]=='@': break else: #no artificial variables self.rows[0] = self.fobj[:] self.phase = 2 return #with artificial variables self.phase = 1 sigma = [fract(-1) if self.vars[i][0]=='@' else fract(0) for i, a in enumerate(self.fobj)] for b, row in zip(self.base, self.rows): if row is None: continue if self.vars[b][0]!='@': continue sigma = [c+v for c,v in zip(sigma,row)] self.rows[0] = sigma
def getX(i, v): if i==0: return '(Obj)', self.getObj() if i in self.base: return v,self.rows[self.base.index(i)][0] if i+1 < len(self.vars) and\ self.vars[i+1][0]=='!' and i+1 in self.base: return v,-self.rows[self.base.index(i)][0] return v, fract(0)
def _best_objective(self): best, idx, sigma = fract(-1), 0, self.rows[0] for i in range(1, self.cols): if sigma[i] <= 0: continue imp = self._improvement(i) if imp is None: return i #infinity if imp <= best: continue #infty can't be converted best, idx = imp, i return idx #0: reached optimality
def fractions(s): lst = s.split() n1 = n2 = x1 = x2 = 0 y1 = y2 = 1 if "+" in lst: mid = lst.index("+") mark = "+" else: mid = lst.index("-") mark = "-" for i in range(mid): if len(lst[i]) == 1: n1 = lst[i] else: [x1, y1] = lst[i].split('/') for i in range(mid, len(lst)): if len(lst[i]) == 1: n2 = lst[i] else: [x2, y2] = lst[i].split('/') [x1, x2, y1, y2, n1, n2] = list(map(int, [x1, x2, y1, y2, n1, n2])) if n1: num1 = n1 * y1 + x1 else: num1 = x1 if n2: num2 = n2 * y2 + x2 else: num2 = x2 if mark == '+': result = fract(num1, y1) + fract(num2, y2) else: result = fract(num1, y1) - fract(num2, y2) n = int(result) dem = result - n if n and not float(dem): print('{}'.format(n)) elif n: print('{} {}'.format(n, str(dem))) else: print('{}'.format(str(dem)))
def _pivot_row(self, col): '''always use "smallest_index" to break tie.''' if self.degenerated: rows = self.degenerated puts("degenerated rows:"+ repr(rows)) else: rows = list(range(1,self.m+1)) rhs = [self.rows[i][0] for i in rows] lhs = [self.rows[i][col] for i in rows] ratio = [r/l for l,r in zip(lhs,rhs) if l>0] if len(ratio) == 0: if not self.degenerated: return 0 #infinite solution #OK, we found a way out of degeneracy! self._restore() return self._pivot_row(col) mrat = min(ratio) #ratio==0: degenerated! nrat = sum(1 for r in ratio if r==mrat) needcare = (mrat == 0 and nrat > 1) if needcare and self.virtual_perturbation: lmin, idx = max(lhs)+1, 0 for i, l, r in zip(rows, lhs, rhs): if r == 0 and (lmin > l > 0): lmin, idx = l, i return idx #which has lmin, to break cycle if needcare and self.flat_wolf: if not self.degenerated: self.vobj = self.rows[0][0] #remember objective value self.degenerated = [i for i in rows if self.rows[i][0]==0] for i in self.degenerated: if self.rows[i][0]: continue #re-randomize? #wolf randomization, without recursion (flat) self.rows[i][0] = fract(1)/randint(2,10) return self._pivot_row(col) smallest, ri = len(self.vars) + 1, -1 for i, l, r in zip(rows, lhs, rhs): #min ratio if l <= 0: continue if r == mrat * l: #fractions if self.base[i] < smallest: smallest, ri = self.base[i], i #smallest_index assert ri >= 0, "row index should never be negative!" return ri #smallest_index
from fractions import Fraction as fract x = set() for i in range(100,1,-1): for z in range(i-1,0, -1): if z/i in x: z-=1 else: x.add(z/i) print(fract(z,i)) print(len(x))#1 to 8 should give len 21
from fractions import Fraction as fract x = set() for i in range(1, 80001): for z in range(int((fract(3, 7) * i) - 1 / i), i): if z / i >= 3 / 7: i += 1 else: print(fract(z, i)) x.add(fract(z, i)) x = sorted(x) print('---', x.pop(), '---')
def _largest_sigma(self): best, idx, sigma = fract(0), 0, self.rows[0] for i in range(1, self.cols): if sigma[i] <= best: continue best, idx = sigma[i], i return idx #0: reached optimality
def terms(td): ts = {} for v,c in td.items(): ts[v] = fract(c) return ts
def __init__(self, prob, interactive=True): '''no variable name should start with '@' in prob.''' self.text = str(prob) self.vars = [''] #reserved def terms(td): ts = {} for v,c in td.items(): ts[v] = fract(c) return ts sts = [(terms(t),r, fract(b)) for t,r,b,p in prob.sts] self.rownames = [p for t,r,b,p in prob.sts] for i, (t,r,b) in enumerate(sts): if i==0: self.obj_dir = r if i==0 and r<0 or i and b < 0: #minimize or b<0 for v in t: t[v] = -t[v] sts[i] = t, -r, -b for v in prob.fvs: #free vars if v not in t: continue t['!%s'%v] = - t[v] #negate coefficient for v in t: if v not in self.vars: self.vars.append(v) self.vars = prob.sortvars(self.vars) #sort by var name self.vars[0] = '(RHS)' #add surplus vars for idx, (t,r,b) in enumerate(sts): if r>=0: continue v = '#%i'%idx t[v] = -1 self.vars.append(v) #add slack vars for idx, (t,r,b) in enumerate(sts): if idx==0 or r<=0: continue v = '$%i'%idx #slack t[v] = 1 self.vars.append(v) #add artificial vars, in the end. #NOTE: not matrix I for idx, (t,r,b) in enumerate(sts): if idx==0 or r>0: continue v = '@%i'%idx #artificial t[v] = 1 self.vars.append(v) #ready for tableau fobj = sts[0][0] self.fobj = [fobj.get(v,0) for v in self.vars] self.origrows = [None] for i, (t,r,b) in enumerate(sts): if i==0: continue #ignore objective row = [t.get(v,0) for v in self.vars] row[0] = b self.origrows.append(row) self._method = Tableau._largest_sigma self.interactive = interactive #The virtual perturbation is not proven self.virtual_perturbation = False #we may also use flat wolf randomization self.flat_wolf = not interactive #degenerated rows for wolf randomization self.degenerated = () self.hist = [] #history, to undo