def matrixFromList(xs, n, p): checkDim(n) checkDim(p) if len(xs) != n * p: error(matrixFromList, "wrong number of elements for input list") matrix = grouped(xs, p) return matrix
def grouped(xs, size): # grouped : List a . Int -> List (List a) if size <= 0: error(grouped, "group size must be non nul natural integer") numberOfGroups = int(len(xs)) / int(size) out = [] for i in range(numberOfGroups): out.append(xs[i * size:(i + 1) * size]) return out
def cgen_if(node): emit_comment('cgen_if') length = len(node.ref_child) if length == 2: cgen_if2(node.ref_child[0], node.ref_child[1]) node.attribute[AttName.has_return] = False elif length == 3: ret = cgen_if1(node.ref_child[0], node.ref_child[1], node.ref_child[2]) node.attribute[AttName.has_return] = (ret == 2) else: error("An illegal pattern used in if statement!") return node
def findBaseDir(newDir): if environ.has_key("WM_PROJECT_INST_DIR"): basedir=environ["WM_PROJECT_INST_DIR"] else: basedir=path.expanduser(config().get("OpenFOAM","Installation")) for bdir in [basedir]+config().getList("OpenFOAM","AdditionalInstallation"): if path.exists(path.join(bdir,"OpenFOAM-"+newDir)): return (bdir,"OpenFOAM-") elif path.exists(path.join(bdir,"openfoam"+newDir)): return (bdir,"openfoam") error("Can't find basedir for OpenFOAM-version",newDir)
def cgen_break(node): emit_comment('cgen_break') parent = node.ref_parent while parent is not None: data = parent.data if data == "whilestmt" or data == "forstmt": break parent = parent.ref_parent if parent is None: error("Error in break statement, break isn't in a loop!") emit_jump(parent.attribute[AttName.exit_label]) return
def valueiteration(v, reward, a): # a = [[None, None, None], [None, None, None], [None, None, None]] # initializing a dummy last value matrix to enter Error loop # vlast = [[1, 0, 0], [0, 0, 0], [0, 0, 0]] # ipdb.set_trace() vlast = generateDummy(v) print(error(v, vlast)) while error(v, vlast) >= 10**(-5): vlast = deepcopy(v) # copying current V in Vlast m = np.shape(v) # size of value matrix for i in range(0, m[0]): # Nos. of Raws for j in range(0, m[1]): # Nos. of Columns for k in range(0, 4): # Nos. of actions if k == 0 and i > 0: # Upper movement for all Raws -1st Raw temp0 = reward[i][j][k] + gama * v[i - 1][j] elif k == 0 and i == 0: # Upper movement for 1st Raw (All Cols) temp0 = None if k == 1 and i < m[ 0] - 1: # Down movement for all raws - last Raw temp1 = reward[i][j][k] + gama * v[i + 1][j] elif k == 1 and i == m[ 0] - 1: # Down movement for last Raw(All Cols) temp1 = None if k == 2 and j > 0: # Left movement for all Cols - 1st Cols temp2 = reward[i][j][k] + gama * v[i][j - 1] elif k == 2 and j == 0: # Left movement for 1st Cols(all raws) temp2 = None if k == 3 and j < m[ 1] - 1: # Right movement for all Cols - last Cols temp3 = reward[i][j][k] + gama * v[i][j + 1] elif k == 3 and j == m[ 1] - 1: # Right movement for last Cols(all raws) temp3 = None v[i][j] = max(temp0, temp1, temp2, temp3) # taking max of all actions # a stores which action is taken to get the value if v[i][j] == temp0: a[i][j] = 0 if v[i][j] == temp1: a[i][j] = 1 if v[i][j] == temp2: a[i][j] = 2 if v[i][j] == temp3: a[i][j] = 3 if v[i][j] == None: v[i][j] = 0 # ipdb.set_trace() return v, a
def crossOverLoopRAND(nbrPath, tab): crossedTabs = [] iteration = 0 for i in range(len(tab)): if(randint(0,len(tab)) > i +3): for j in range(i,len(tab)): if(iteration + len(tab) < nbrPath): iteration += 1 crossedTabs.append( crossOverPath2(tab[i],tab[j])) else: if crossedTabs: return crossedTabs else: error("Le cross_over ne s'est fait pas fait") return crossedTabs
def crossOverLoopClassique(nbrPath, tab, Map): crossedTabs = [] iteration = 0 nbr = floor(0.5*len(tab[0])) for i in range(nbrPath - len(tab)): for j in range(i,len(tab)): if(iteration + len(tab) < nbrPath): iteration += 1 crossedTabs.append( singlePoint(nbr,tab[i],tab[j])) else: if crossedTabs: return crossedTabs else: error("Le cross_over ne s'est fait pas fait") return crossedTabs
def errorCheck(self, size, MAX, MIN): if (type(size) is not int): error("Map creation : size is a " + str(type(size)) + ": To create a map you need an int") if (type(MAX) is not int): error("Map creation : MAX is a " + str(type(MAX)) + ": To create a map you need an int") if (type(MIN) is not int): error("Map creation : MIN is a " + str(type(MIN)) + ": To create a map you need an int") if (MIN > MAX): error("Map creation : MIN is a greater than MAX")
def changeFoamVersion(new,force64=False,force32=False,compileOption=None): """Changes the used FoamVersion. Only valid during the runtime of the interpreter (the script or the Python session) @param new: The new Version @param force64: Forces the 64-bit-version to be chosen @param force32: Forces the 32-bit-version to be chosen @param compileOption: Forces Debug or Opt""" if not new in foamInstalledVersions(): error("Version",new,"is not an installed version: ",foamInstalledVersions()) old=None if environ.has_key("WM_PROJECT_VERSION"): old=environ["WM_PROJECT_VERSION"] if new==old: warning(new,"is already being used") else: warning("No OpenFOAM-Version installed") basedir,prefix=findBaseDir(new) if path.exists(path.join(basedir,prefix+new,"etc")): script=path.join(basedir,prefix+new,"etc","bashrc") else: script=path.join(basedir,prefix+new,".OpenFOAM-"+new,"bashrc") forceArchOption=None if force64: forceArchOption="64" elif force32: forceArchOption="32" injectVariables(script, forceArchOption=forceArchOption, compileOption=compileOption) try: if old==environ["WM_PROJECT_VERSION"]: warning("Problem while changing to version",new,"old version still used:",environ["WM_PROJECT_VERSION"]) except KeyError: pass
def injectVariables(script,forceArchOption=None,compileOption=None): """Executes a script in a subshell and changes the current environment with the enivironment after the execution @param script: the script that is executed @param forceArchOption: To which architecture Option should be forced @param compileOption: to which value the WM_COMPILE_OPTION should be forced""" try: # Certan bashrc-s fail if this is set del environ["FOAM_INST_DIR"] except KeyError: pass if not path.exists(script): error("Can not execute",script,"it does not exist") try: if environ.has_key("SHELL"): shell=environ["SHELL"] if(path.basename(shell).find("python")==0): # this assumes that the 'shell' is a PyFoam-Script on a cluster shell=config().get("Paths","bash") environ["SHELL"]=shell allowedShells = [ "bash", "zsh"] if not path.basename(shell) in allowedShells: error("Currently only implemented for the shells",allowedShells,", not for",shell) cmd="" postCmd="" if forceArchOption!=None: cmd+="export WM_ARCH_OPTION="+forceArchOption+"; " postCmd+=" WM_ARCH_OPTION="+forceArchOption if compileOption!=None: cmd+="export WM_COMPILE_OPTION="+compileOption+"; " postCmd+=" WM_COMPILE_OPTION="+compileOption cmd+=". "+script+postCmd+'; echo "Starting The Dump Of Variables"; export' except KeyError,name: error("Can't do it, because shell variable",name,"is undefined")
def dp(S, gap_penalty): """ @summary: Solves optimal path in score matrix based on global sequence alignment @param S: Score matrix @type S: numpy. @param gap_penalty: Gap penalty @type gap_penalty: FloatType @return: A dictionary of results @rtype: DictType @author: Tim Erwin """ #comm = MPI.COMM_WORLD #rank = comm.Get_rank() #print " In DP.py, I am rank", rank try: row_length = len(S[:,0]) except(IndexError): error('Zero length alignment found: Samples with no peaks \ cannot be aligned') col_length = len(S[0,:]) #D contains the score of the optimal alignment D = numpy.zeros((row_length+1,col_length+1), dtype='d') for i in range(1, row_length+1): D[i,0] = gap_penalty*i for j in range(1, col_length+1): D[0,j] = gap_penalty*j D[0,0] = 0.0 D[1:(row_length+1), 1:(col_length+1)] = S.copy(); # Directions for trace # 0 - match (move diagonal) # 1 - peaks1 has no match (move up) # 2 - peaks2 has no match (move left) # 3 - stop trace_matrix = numpy.zeros((row_length+1,col_length+1)) trace_matrix[:,0] = 1; trace_matrix[0,:] = 2; trace_matrix[0,0] = 3; for i in range(1,row_length+1): for j in range(1,col_length+1): # # Needleman-Wunsch Algorithm assuming a score function S(x,x)=0 # # | D[i-1,j-1] + S(i,j) # D[i,j] = min | D(i-1,j] + gap # | D[i,j-1] + gap # darray = [D[i-1,j-1]+S[i-1,j-1], D[i-1,j]+gap_penalty, D[i,j-1]+gap_penalty] D[i,j] = min(darray) #Store direction in trace matrix trace_matrix[i,j] = darray.index(D[i,j]) # Trace back from bottom right trace = [] matches = [] i = row_length j = col_length direction = trace_matrix[i,j] p = [row_length-1] q = [col_length-1] while direction != 3: if direction == 0: #Match i = i-1 j = j-1 matches.append([i,j]) elif direction == 1: #peaks1 has no match i = i-1 elif direction == 2: #peaks2 has no match j = j-1 p.append(i-1) q.append(j-1) trace.append(direction) direction=trace_matrix[i,j] #remove 'stop' entry p.pop() q.pop() # reverse the trace back p.reverse() q.reverse() trace.reverse() matches.reverse() return {'p':p, 'q':q, 'trace':trace, 'matches':matches, 'D':D, 'phi':trace_matrix}
def check_points(points): for r in points: if r.y <= 0: error("Y is neg")
def checkIx(index, limit): if index < 0 or index >= limit: error( checkIx, "index must be a natural integer inferior to " + "limit = " + str(limit))
def checkDim(dim): if dim <= 0: error(checkDim, "dimensions must be non null positive integers")
def nrows(matrix): if len(matrix) == 0: error(nrows, "input matrix is an empty list") return len(matrix)
def dp(S, gap_penalty): """ @summary: Solves optimal path in score matrix based on global sequence alignment @param S: Score matrix @type S: numpy. @param gap_penalty: Gap penalty @type gap_penalty: FloatType @return: A dictionary of results @rtype: DictType @author: Tim Erwin """ #comm = MPI.COMM_WORLD #rank = comm.Get_rank() #print " In DP.py, I am rank", rank try: row_length = len(S[:, 0]) except (IndexError): error('Zero length alignment found: Samples with no peaks \ cannot be aligned') col_length = len(S[0, :]) #D contains the score of the optimal alignment D = numpy.zeros((row_length + 1, col_length + 1), dtype='d') for i in range(1, row_length + 1): D[i, 0] = gap_penalty * i for j in range(1, col_length + 1): D[0, j] = gap_penalty * j D[0, 0] = 0.0 D[1:(row_length + 1), 1:(col_length + 1)] = S.copy() # Directions for trace # 0 - match (move diagonal) # 1 - peaks1 has no match (move up) # 2 - peaks2 has no match (move left) # 3 - stop trace_matrix = numpy.zeros((row_length + 1, col_length + 1)) trace_matrix[:, 0] = 1 trace_matrix[0, :] = 2 trace_matrix[0, 0] = 3 for i in range(1, row_length + 1): for j in range(1, col_length + 1): # # Needleman-Wunsch Algorithm assuming a score function S(x,x)=0 # # | D[i-1,j-1] + S(i,j) # D[i,j] = min | D(i-1,j] + gap # | D[i,j-1] + gap # darray = [ D[i - 1, j - 1] + S[i - 1, j - 1], D[i - 1, j] + gap_penalty, D[i, j - 1] + gap_penalty ] D[i, j] = min(darray) #Store direction in trace matrix trace_matrix[i, j] = darray.index(D[i, j]) # Trace back from bottom right trace = [] matches = [] i = row_length j = col_length direction = trace_matrix[i, j] p = [row_length - 1] q = [col_length - 1] while direction != 3: if direction == 0: #Match i = i - 1 j = j - 1 matches.append([i, j]) elif direction == 1: #peaks1 has no match i = i - 1 elif direction == 2: #peaks2 has no match j = j - 1 p.append(i - 1) q.append(j - 1) trace.append(direction) direction = trace_matrix[i, j] #remove 'stop' entry p.pop() q.pop() # reverse the trace back p.reverse() q.reverse() trace.reverse() matches.reverse() return { 'p': p, 'q': q, 'trace': trace, 'matches': matches, 'D': D, 'phi': trace_matrix }
def isolateItem(xs, index): # isolateItem : List a . Index -> (a, List a) if outOfRange(index, xs): error(isolateItem, "out of range index") rest = xs[:index] + xs[index + 1:] return (xs[index], rest)
def ncols(matrix): if len(matrix) == 0: error(ncols, "input matrix is an empty list") return len(matrix[0])