def main(): import sys import transpose TopScoreOut = open(sys.argv[1].rstrip('.tmp')+'_TopScores','w') Lines = [Line for Line in open(sys.argv[1])] CutOff = float(sys.argv[2]) Lines_t = transpose.transpose(Lines) Scores = [] for Index,Feature in enumerate(Lines_t[2:]): FList = Feature.split() length = len(FList) MemberClass = [float(val) for val in FList[:length/2] if val != 'NaN'] VagabondClass = [float(val) for val in FList[length/2:] if val != 'NaN'] if len(MemberClass) < 3 or len(VagabondClass) < 3: continue Scores.append((Index+1,calculate_fisher_criterion(MemberClass,VagabondClass,ABS="True"))) Scores.sort(key=lambda x:x[1]) TopScoreDict = {} for Score in Scores[:int(CutOff*len(Scores))]: TopScoreDict[int(Score[0])] = Score[1] TopScoreOut.write(str(Score[0])+'\n') TopScoreOut.close() try: OutPut_t = ['F#:\t'+ Lines_t[0]] except IndexError: print Lines_t raise OutPut_t.append('C:\t'+Lines_t[1]) for Index,Feature in enumerate(Lines_t[2:]): if TopScoreDict.has_key(Index+1): OutPut_t.append(str(Index+1)+'\t'+Feature) OutPut = transpose.transpose(OutPut_t) if len(sys.argv) == 4: Joiner = '\t'+sys.argv[3] InsertTarg = OutPut[0] TargSplitList = InsertTarg.split() Start = TargSplitList[0]+'\t'+TargSplitList[1]+'\t' Inserted = sys.argv[3]+Joiner.join(TargSplitList[2:]) NewHead = Start+Inserted OutPut[0] = NewHead for Line in OutPut: print Line.rstrip()
def test_mixed_line_length(self): input_line = [ "The longest line.", "A long line.", "A longer line.", "A line." ] expected = [ "TAAA", "h ", "elll", " ooi", "lnnn", "ogge", "n e.", "glr", "ei ", "snl", "tei", " .n", "l e", "i .", "n", "e", "." ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_empty_string(self): input_line = "" expected = "" self.assertEqual( transpose(input_line), expected )
def test_first_line_longer_than_second_line(self): input_line = [ "The fourth line.", "The fifth line." ] expected = [ "TT", "hh", "ee", " ", "ff", "oi", "uf", "rt", "th", "h ", " l", "li", "in", "ne", "e.", "." ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_empty_string(self): lines = [] expected = [] self.assertEqual( transpose("\n".join(lines)), "\n".join(expected) )
def test_second_line_longer_than_first_line(self): input_line = [ "The first line.", "The second line." ] expected = [ "TT", "hh", "ee", " ", "fs", "ie", "rc", "so", "tn", " d", "l ", "il", "ni", "en", ".e", " ." ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def main(): import sys import transpose TopScoreOut = open(sys.argv[1].rstrip('.tmp')+'_TopScores','w') Lines = [Line for Line in open(sys.argv[1])] CutOff = float(sys.argv[2]) Lines_t = transpose.transpose(Lines) Scores = [] for Index,Feature in enumerate(Lines_t[2:]): FList = Feature.split() length = len(FList) MemberClass = [int(val) for val in FList[:length/2] if val == '1'] VagabondClass = [int(val) for val in FList[:length/2] if val == '1'] MCount = sum(MemberClass) VCount = sum(VagabondClass) Score = (MCount-VCount)**2 Scores.append((Index+1,Score)) Scores.sort(key=lambda x:x[1]) TopScoreDict = {} for Score in Scores[:int(CutOff*len(Scores))]: TopScoreDict[int(Score[0])] = Score[1] TopScoreOut.write(str(Score[0])+'\n') TopScoreOut.close() OutPut_t = ['F#:\t'+ Lines_t[0]] OutPut_t.append('C:\t'+Lines_t[1]) for Index,Feature in enumerate(Lines_t[2:]): if TopScoreDict.has_key(Index+1): OutPut_t.append(str(Index+1)+'\t'+Feature) OutPut = transpose.transpose(OutPut_t) if len(sys.argv) == 4: Joiner = '\t'+sys.argv[3] InsertTarg = OutPut[0] TargSplitList = InsertTarg.split() Start = TargSplitList[0]+'\t'+TargSplitList[1]+'\t' Inserted = sys.argv[3]+Joiner.join(TargSplitList[2:]) NewHead = Start+Inserted OutPut[0] = NewHead for Line in OutPut: print Line.rstrip()
def test_two_characters_in_a_column(self): input_line = [ "A", "1" ] expected = "A1" self.assertEqual( transpose("\n".join(input_line)), expected )
def render(self, library, next_word): phonemes = library.build(db.pronounce(self.word)) audio_out = numpy.concatenate(i.render() for i in phonemes) pitch_initial = moods[self.mood][word.transpose] pitch_final = moods[next_word.mood][next_word.transpose] timescale = word.timescale # TODO: interpolation? return transpose.transpose(audio_out, pitch_initial, timescale)
def test_two_characters_in_a_row(self): input_line = "A1" expected = [ "A", "1" ] self.assertEqual( transpose(input_line), "\n".join(expected) )
def test_two_characters_in_a_column(self): lines = [ "A", "1" ] expected = [ "A1" ] self.assertEqual( transpose("\n".join(lines)), "\n".join(expected) )
def test_simple(self): input_line = [ "ABC", "123" ] expected = [ "A1", "B2", "C3" ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def pretty_chord(chord, key, transposition, unicodeAdjustments=False): """ Форматирование аккорда :type chord: str or unicode :type key: unicode :type transposition: unicode :rtype: unicode """ chord = unicode(chord) chord = CHORD.sub(lambda m: transpose(m.group(1), key, transposition), chord) if unicodeAdjustments: chord = chord.replace('b', u'\u266D') chord = chord.replace('#', u'\u266F') return chord
def test_square(self): input_line = [ "HEART", "EMBER", "ABUSE", "RESIN", "TREND" ] expected = [ "HEART", "EMBER", "ABUSE", "RESIN", "TREND" ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_single_line(self): input_line = ["Single line."] expected = [ "S", "i", "n", "g", "l", "e", " ", "l", "i", "n", "e", "." ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_rectangle(self): input_line = [ "FRACTURE", "OUTLINED", "BLOOMING", "SEPTETTE" ] expected = [ "FOBS", "RULE", "ATOP", "CLOT", "TIME", "UNIT", "RENT", "EDGE" ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_triangle(self): input_line = [ "T", "EE", "AAA", "SSSS", "EEEEE", "RRRRRR" ] expected = [ "TEASER", " EASER", " ASER", " SER", " ER", " R" ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_two_characters_in_a_row(self): input_line = "A1" expected = "A\n1" self.assertEqual(transpose(input_line), expected)
'''Calculating errors in outlet liquid flow rates''' e1 = C_co2_result[n-1]-C_co2[n-1]; #CO2 e2 = C_meth_result[n-1]-C_meth[n-1]; #CH4 e3 = L_water_result[n-1]-L_water[n-1]; #Liquid Water err = abs(e1) + abs(e2) + abs(e3); #Total error (always positive) '''Error Generating/ Changing Functions''' L_co2_guess = L_co2_guess - (e1/10); #CO2 L_meth_guess = L_meth_guess - (e2/10); #CH4 L_water_guess = L_water_guess - (e3/10); #Liquid Water itr = itr + 1; '''FINAL LIQUID MOLAR FLOW RATES''' from transpose import transpose L_co2 = transpose(L_co2_result); L_meth = transpose(L_meth_result); L_water = transpose(L_water_result); '''FINAL DISSOLVED CONCENTRATIONS''' C_co2 = transpose(C_co2_result); C_meth = transpose(C_meth_result); '''EXIT CONCENTRATIONS''' import numpy as np exit = np.column_stack((C_co2_result,C_meth)); #The height of the column is assumed from the ground level, i.e., element 1 is closest to ground. print 'The concentrations of CO2 and CH4 dissolved in water from bottom to top respectively are (in kmol/m3): \n' print exit '''PLOTTING VARIOUS GRAPHS'''
def test_empty_string(self): lines = [] expected = [] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
def test_simple(self): lines = ["ABC", "123"] expected = ["A1", "B2", "C3"] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
from transpose import transpose matrix = [[1, 0], [0, 4]] print("matrix") print(transpose(matrix)) matrix2 = [[1, 2, 5], [3, 4, 5], [4, 7, 9]] print("matrix2") print(transpose(matrix2))
def test_empty_string(self): input_line = "" expected = "" self.assertEqual(transpose(input_line), expected)
def test_two_characters_in_a_row(self): input_line = "A1" expected = ["A", "1"] self.assertEqual(transpose(input_line), "\n".join(expected))
def test_two_rows(self): self.assertEqual(transpose([[1, 2], [3, 4]]), [[1, 3], [2, 4]])
def test_three_rows(self): inputs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] outputs = [[1, 4, 7], [2, 5, 8], [3, 6, 9]] self.assertEqual(transpose(inputs), outputs)
def test_rectangle(self): lines = ["FRACTURE", "OUTLINED", "BLOOMING", "SEPTETTE"] expected = [ "FOBS", "RULE", "ATOP", "CLOT", "TIME", "UNIT", "RENT", "EDGE" ] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
def test_empty(self): self.assertEqual(transpose([]), [])
def test_two_characters_in_a_column(self): self.assertEqual( transpose("\n".join(["A", "1"])), "A1" )
def test_many_lines(self): input_line = [ "Chor. Two households, both alike in dignity,", "In fair Verona, where we lay our scene,", "From ancient grudge break to new mutiny,", "Where civil blood makes civil hands unclean.", "From forth the fatal loins of these two foes", "A pair of star-cross'd lovers take their life;", "Whose misadventur'd piteous overthrows", "Doth with their death bury their parents' strife.", "The fearful passage of their death-mark'd love,", "And the continuance of their parents' rage,", "Which, but their children's end, naught could remove,", "Is now the two hours' traffic of our stage;", "The which if you with patient ears attend,", "What here shall miss, our toil shall strive to mend." ] expected = [ "CIFWFAWDTAWITW", "hnrhr hohnhshh", "o oeopotedi ea", "rfmrmash cn t", ".a e ie fthow ", " ia fr weh,whh", "Trnco miae ie", "w ciroitr btcr", "oVivtfshfcuhhe", " eeih a uote ", "hrnl sdtln is", "oot ttvh tttfh", "un bhaeepihw a", "saglernianeoyl", "e,ro -trsui ol", "h uofcu sarhu ", "owddarrdan o m", "lhg to'egccuwi", "deemasdaeehris", "sr als t ists", ",ebk 'phool'h,", " reldi ffd ", "bweso tb rtpo", "oea ileutterau", "t kcnoorhhnatr", "hl isvuyee'fi ", " atv es iisfet", "ayoior trr ino", "l lfsoh ecti", "ion vedpn l", "kuehtteieadoe ", "erwaharrar,fas", " nekt te rh", "ismdsehphnnosa", "ncuse ra-tau l", " et tormsural", "dniuthwea'g t ", "iennwesnr hsts", "g,ycoi tkrttet", "n ,l r s'a anr", "i ef 'dgcgdi", "t aol eoe,v", "y nei sl,u; e", ", .sf to l ", " e rv d t", " ; ie o", " f, r ", " e e m", " . m e", " o n", " v d", " e .", " ," ] self.assertEqual( transpose("\n".join(input_line)), "\n".join(expected) )
def test_two_characters_in_a_column(self): self.assertEqual(transpose("\n".join(["A", "1"])), "A1")
def test_two_characters_in_a_row(self): lines = ["A1"] expected = ["A", "1"] # print("....",transpose(lines),"........", expected, ".....", transpose("\n".join(lines)), "....", "\n".join(expected)) self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
s = 10 #substrate input-feed ph = 7 #initially n = 10 #grid points ''' fig=plt.figure() ax=fig.add_subplot(111) ''' t = numpy.linspace(0, 1, 10) #for hydrolytic microbe xh = numpy.exp(((uhmax * s) / (Khs + s) - khd) * t) from transpose import transpose print transpose(xh) #for acetogenic microbe def ODEA(xa, t): da = -(uamax * xa * xa) / (Kas * ya - xa) - kad * xa return da def ODEM(xm, t): dm = -(ummax * xm * xm) / (Kms * ym - xm) - kmd * xm return dm xa = odeint(ODEA, 10, t) xm = odeint(ODEM, 10, t)
def ODEM2(xm,t): dm=-(ummax*xm*xm)/(1+(10**(-ph)/km2)+km1/(10**(-ph)))-kmd*(xm-xa1) return dm if xa1>(xainit/2): xm=odeint(ODEM,xminit,t) else: xm=odeint(ODEM2,xminit,t) ph=-numpy.log10(xa/v) #variation of ph with acetogenic microbe amount ds=-xh/yh #change in substrate amount due to consumption s=s-ds #new substrate amount after one cycle print transpose (xh) print xa print xm #plt.plot(t, xa, 'r--', t, xh, 'bs', t, xm, 'g^') #plt.show() fig, ax = plt.subplots() ax.set_ylim(0, 20) ax.set_xlim(0, 10) ax.grid() xdata, ydata = [], [] def run(data): # update the data
def test_two_characters_in_a_column(self): input_line = ["A", "1"] expected = "A1" self.assertEqual(transpose("\n".join(input_line)), expected)
def counter_abs(self): L = self.L; #Length of absorber (m) A = self.A; #Cross- sectional area of absorber (m2) T = self.T; #Temperature (K) P = self.P; #Pressure (Pa) n = self.n; #Number of elements in pipe dz = L/(n-1); #Length of each element (m) V_water = 18*1e-3; #Volume of 1 kmol liquid water '''OVERALL MASS TRANSFER COEFFICIENTS (1/s) * INTERFACIAL AREA (m2/m3) The kla values have been obtained from pg. 19-42, Table 19-10, Perry's Chemical Engineers' Handbook (8th Edition). The values given below are for representative purposes only. Actual values may be calculated from the various correlations available.''' kla_co2 = 0.002; #for CO2 based on liquid side kla_meth = 0.001; #for Methane based on liquid side kga = 0.0005; #for water vapour based on gas side '''HENRY'S CONSTANTS (atm) The Henry's constants have been obtained from pg. 2-130, Table 2-123 (for CO2) and Table 2-124 (for CH4), Perry's Chemical Engineers' Handbook (Edition 8).''' from H2SI import H2SI H_meth = 36600; #atm H_co2 = 1635 #atm #conversion to SI units H_meth = H2SI(H_meth); H_co2 = H2SI(H_co2); '''The antoine coefficients for water have been taken from pg. 682, Appendix B, Table B2, Chemical Engineering Thermodynamics, Smmith Van Ness (Edition 7). The saturation vapour pressure returned is in Pascal.''' from P_sat_water import P_sat_water P_sat_water = P_sat_water(T); #Pascal '''OVERALL MOLAR FLOW RATE OF GAS The units of flow rate are taken to be kmol/s. The gas phase contains CO2, CH4 and water vapour. The mole fractions of the various components of the gas phase have been subsequently mentioned.''' G_gas = [None]*n; #Initialising an array of molar flow rates G_gas[0] = 100; #Gas Flow Rate at bottom of absorber (kmol/s); '''The various parameters (element-wise) for the various cpmponents have been defined in the following lines of code. These parameters include: 1) Gas molar Flow Rate (kmol/s) 2) Mole Fraction in gas phase 3) Partial Pressures in gas phase (Pa) 3) Concentration in water (kmol/m3) 4) Molar flow rate of dissolved component''' '''METHANE''' G_meth = [None]*n; #Initialising an array of molar flow rates of CH4 (kmol/s) X_meth_gas = [None]*n; #Mole fraction of CH4 in gas phase X_meth_gas[0] = 0.5; #Inlet mole fraction of CH4 in gas phase P_meth = [None]*n; #Partial Pressure of CH4 (Pa) C_meth = [None]*n; #Concentration of CH4 in liquid phase (kmol/m3) C_meth[n-1] = 0; #Concentration of CH4 in liquid phase at entry (kmol/m3) L_meth = [None]*n; #Molar flow rate of dissolved CH4 in water (kmol/s) '''CARBON DIOXIDE''' G_co2 = [None]*n; #Initialising an array of molar flow rates of CH4 (kmol/s) X_co2_gas = [None]*n; #Mole fraction of CO2 in gas phase X_co2_gas[0] = 0.5; #Inlet mole fraction of CO2 in gas phase P_co2 = [None]*n; #Partial Pressure of CO2 (Pa) C_co2 = [None]*n; #Concentration of CO2 in liquid phase (kmol/m3) C_co2[n-1] = 0; #Concentration of C02 in liquid phase at entry (kmol/m3) L_co2 = [None]*n; #Molar flow rate of dissolved C02 in water (kmol/s) '''WATER AND WATER VAPOUR''' '''There is no such thing as a concentration driving force for water.''' G_water = [None]*n; #Initialising an array of molar flow rates of water vapour (kmol/s) X_water = [None]*n; #Mole fraction of water vapour in gas phase X_water[0] = 0; #Inlet mole fraction of water vapour in gas phase P_water = [None]*n; #Initialising an array of partial pressures of water vapour (Pa) L_water = [None]*n; #Initialising an array of molar flow rates of liquid water (kmol/s) L_water[n-1] = 100; #Input molar flow rate of liquid water (kmol/s) '''ALGORITHM FOR SOLVING THE DIFFERENTIAL EQUATIONS OF RATE OF MASS TRANSFER 1) Euler's explicit method is used to discretize the equations. This is a BVP. 2) Guess values of exit liquid flow rates for all the components are taken. 3) The input values are back calculated and the error is obtained. 4) This obtained is used to obtain a new value of guess value. 5) The above procedure is repeated until the solution has converged (SHOOTING METHOD).''' '''GUESS VALUES FOR EXIT LIQUID FLOW RATES''' L_meth_guess = 0.05; #Guess value for dissolved CH4 (kmol/s) L_co2_guess = 0.01; #Guess value for dissolved CO2 (kmol/s) L_water_guess = 95; #Guess value for liquid water (kmol/s) '''ARRAYS FOR STORING BACK CALCULATED VALUES OF LIQUID MOLAR FLOW RATES''' L_meth_result = [None]*n; #For dissolved CH4 (kmol/s) L_co2_result = [None]*n; #For dissolved CO2 (kmol/s) L_water_result = [None]*n; #For liquid water (kmol/s) '''ARRAYS FOR STORING THE CALCULATED VALUES OF DISSOLVED CONCENTRATIONS''' C_co2_result = [None]*n; #For dissolved CO2 (kmol/m3) C_meth_result = [None]*n; #For dissolved CH4 (kmol/m3) '''DEFINING GUESS ERROR LIMITS BASED ON TOP LIQUID MOLAR FLOW RATES''' e1 = 1; #For dissolved CO2 e2 = 1; #For dissolved CH4 e3 = 1; #For liquid water err = abs(e1) + abs(e2) + abs(e3); #Total error itr = 0; #iteration counter while err>0.0000001: for i in range(n-1): L_water_result[0] = L_water_guess; L_meth_result[0] = L_meth_guess; L_co2_result[0] = L_co2_guess; '''Calculation of exit concentration of dissolved CO2''' C_co2_result[0] = L_co2_result[0]/(L_water_result[0]*V_water); '''Calculation of exit concentration of dissolved CH4''' C_meth_result[0] = L_meth_result[0]/(L_water_result[0]*V_water); '''Molar gas flow rates (kmol/s)''' G_co2[i] = G_gas[i]*X_co2_gas[i]; #CO2 G_meth[i] = G_gas[i]*X_meth_gas[i]; #CH4 G_water[i] = G_gas[i]*X_water[i]; #Water vapour '''Partial Pressures (Pa)''' P_meth[i] = P*X_meth_gas[i]; #CH4 P_co2[i] = P*X_co2_gas[i]; #CO2 P_water[i] = P*X_water[i]; #Water vapour '''Solving mass transfer equation for CO2 (both liquid as well as gas)''' G_co2[i+1] = G_co2[i] + kla_co2*A*dz*(C_co2_result[i]- (P_co2[i]/H_co2)); #Gas L_co2_result[i+1] = L_co2_result[i] + kla_co2*A*dz*(C_co2_result[i]- (P_co2[i]/H_co2)); #Liquid '''Solving mass transfer equation for CH4 (both liquid as well as gas)''' G_meth[i+1] = G_meth[i] + kla_meth*A*dz*(C_meth_result[i]- (P_meth[i]/H_meth)); #Gas L_meth_result[i+1] = L_meth_result[i] + kla_meth*A*dz*(C_meth_result[i]- (P_meth[i]/H_meth)); #Liquid '''Solving mass transfer equation for Water and Water Vapour''' G_water[i+1] = G_water[i] + kga*A*dz*(P_sat_water-P_water[i]); #Water L_water_result[i+1] = L_water_result[i] + kga*A*dz*(P_sat_water-P_water[i]); #Water Vapour '''Calculating Values of dissolved concentrations of CO2 and CH4''' C_co2_result[i+1] = L_co2_result[i+1]/(L_water_result[i+1]*18*1e-3); #CO2 C_meth_result[i+1] = L_meth_result[i+1]/(L_water_result[i+1]*18*1e-3); #CH4 '''Total molar gas flow rates at i+1 element''' G_gas[i+1] = G_co2[i+1] + G_meth[i+1] + G_water[i+1]; '''Calculating gas phase mole fractions for i+1 element''' X_co2_gas[i+1] = G_co2[i+1]/G_gas[i+1]; #CO2 X_meth_gas[i+1] = G_meth[i+1]/G_gas[i+1]; #CH4 X_water[i+1] = G_water[i+1]/G_gas[i+1]; #Water vapour '''Calculating errors in outlet liquid flow rates''' e1 = C_co2_result[n-1]-C_co2[n-1]; #CO2 e2 = C_meth_result[n-1]-C_meth[n-1]; #CH4 e3 = L_water_result[n-1]-L_water[n-1]; #Liquid Water err = abs(e1) + abs(e2) + abs(e3); #Total error (always positive) '''Error Generating/ Changing Functions''' L_co2_guess = L_co2_guess - (e1/10); #CO2 L_meth_guess = L_meth_guess - (e2/10); #CH4 L_water_guess = L_water_guess - (e3/10); #Liquid Water itr = itr + 1; '''FINAL LIQUID MOLAR FLOW RATES''' from transpose import transpose L_co2 = transpose(L_co2_result); L_meth = transpose(L_meth_result); L_water = transpose(L_water_result); '''FINAL DISSOLVED CONCENTRATIONS''' C_co2 = transpose(C_co2_result); C_meth = transpose(C_meth_result); '''EXIT CONCENTRATIONS''' import numpy as np exit = np.column_stack((C_co2_result,C_meth)); #The height of the column is assumed from the ground level, i.e., element 1 is closest to ground. print 'The concentrations of CO2 and CH4 dissolved in water from bottom to top respectively are (in kmol/m3): \n' '''PLOTTING VARIOUS GRAPHS''' z = [None]*n; for i in range(n): z[i] = i*dz; '''PLOTTING DATA''' import matplotlib.pyplot as plt plt.figure('Concentration Profiles') plt.subplots_adjust(left = 0.2,right = 0.95,wspace = 1, hspace = 0.5) plt.subplot(211) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.title('Concentration of CO2 vs. Height'); plt.xlabel('Height (m)'); plt.ylabel('Concentration of CO2 (kmol/m3)'); plt.plot(z,C_co2_result,'b') plt.show() plt.subplot(212) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.title('Concentration of CH4 vs. Height'); plt.xlabel('Height (m)'); plt.ylabel('Concentration of CH4 (kmol/m3)'); plt.plot(z,C_meth_result,'r') plt.show() return exit, G_water
def main(): argparser = argparse.ArgumentParser(description="text file") argparser.add_argument("file", type=str, help="file to produce frequency distribution for") argparser.add_argument("-m", "--pLen", type=int, default=4, help="length of the patterns to look for") argparser.add_argument("-n", "--nRes", type=int, default=5, help="number of results to show") argparser.add_argument("-k", "--findKey", help="find patterns from repeating key", action="store_true") argparser.add_argument( "-p", "--plotByAlpha", help="-p N: split cipher text by N alphabets and save plots. specify dir to save with -d. default is the current directory", type=int, default=0, ) argparser.add_argument("-l", "--cipherLen", help="display the length of the cipher text", action="store_true") argparser.add_argument("-d", "--outDir", type=str, default=".", help="directory to save files to") argparser.add_argument("-a", "--ascii", help="text is ascii", action="store_true") argparser.add_argument( "-s", "--shiftByAlpha", help="-s N: split cipher text by N alphabets and shift on the basis of frequency analysis", type=int, default=0, ) argparser.add_argument("-r", "--reverseShift", help="shift charcters backwards", action="store_true") argparser.add_argument( "-x", "--xorByAlpha", help="-x N: split cipher text by N alphabets and xor on the basis of frequency analysis", type=int, default=0, ) argparser.add_argument("-c", "--common", help="most common letter in plain text alphabet", default="e") argparser.add_argument( "-g", "--grid", help="-g N: output the cipher text in a grid N chars wide", type=int, default=0 ) argparser.add_argument( "-t", "--transpose", help="-t N: output the cipher text in a grid N chars wide", metavar="N", nargs="+", type=int, default=0, ) argparser.add_argument( "-i", "--perpGrid", help="-g N: output the cipher text in a grid N chars wide", type=int, default=0 ) args = argparser.parse_args() toker = WhitespaceTokenizer() f = open(args.file) if args.ascii: text = f.read().split() arry = [] for e in text: arry.append(chr(int(e, 16))) # ascString = string.join(arry) ascString = arry else: ascString = f.read() tmp = "" for c in ascString: if ord(c) < 128: tmp = tmp + c ascString = tmp if args.cipherLen: print("cipher text length: " + str(len(ascString))) if args.findKey: print(findKey.getNgramsDispersion(string.join(ascString), args.pLen, args.nRes)) if args.plotByAlpha > 0: alphas = split.splitByAlpha(args.plotByAlpha, ascString) g = 0 for group in alphas: g += 1 myFreqDist.MyFreqDist(group).createPlot(args.outDir + "s" + str(args.plotByAlpha) + "g" + str(g), 10) if args.shiftByAlpha > 0: alphas = split.splitByAlpha(args.shiftByAlpha, ascString) candidate = shift.shiftByAlpha(alphas, ascString, args.common, args.reverseShift) file = open(args.outDir + "candidate.pln", "w") print(candidate) if args.xorByAlpha > 0: alphas = split.splitByAlpha(args.xorByAlpha, ascString) candidate = xor.xorByAlpha(alphas, ascString, args.common) file = open(args.outDir + "candidate.pln", "w") print(candidate) if args.grid > 0: grid.grid(ascString, args.grid) if args.perpGrid > 0: perpGrid.grid(ascString, args.perpGrid) if len(args.transpose) > 0: transpose.transpose(ascString, args.transpose)
def main(): argparser = argparse.ArgumentParser(description='text file') argparser.add_argument('file', type=str, help='file to produce frequency distribution for') argparser.add_argument('-m', '--pLen', type=int, default=4, help='length of the patterns to look for') argparser.add_argument('-n', '--nRes', type=int, default=5, help='number of results to show') argparser.add_argument('-k', '--findKey', help='find patterns from repeating key', action='store_true') argparser.add_argument('-p', '--plotByAlpha', help='-p N: split cipher text by N alphabets and save plots. specify dir to save with -d. default is the current directory', type=int, default=0) argparser.add_argument('-l', '--cipherLen', help='display the length of the cipher text', action='store_true') argparser.add_argument('-d', '--outDir', type=str, default='.', help='directory to save files to') argparser.add_argument('-a', '--ascii', help='text is ascii', action='store_true') argparser.add_argument('-s', '--shiftByAlpha', help='-s N: split cipher text by N alphabets and shift on the basis of frequency analysis', type=int, default=0) argparser.add_argument('-r', '--reverseShift', help='shift charcters backwards', action='store_true') argparser.add_argument('-x', '--xorByAlpha', help='-x N: split cipher text by N alphabets and xor on the basis of frequency analysis', type=int, default=0) argparser.add_argument('-c', '--common', help='most common letter in plain text alphabet', default='e') argparser.add_argument('-g', '--grid', help='-g N: output the cipher text in a grid N chars wide', type=int, default=0) argparser.add_argument('-t', '--transpose', help='-t N: output the cipher text in a grid N chars wide', metavar='N', nargs='+', type=int, default=0) argparser.add_argument('-i', '--perpGrid', help='-g N: output the cipher text in a grid N chars wide', type=int, default=0) args = argparser.parse_args() toker = WhitespaceTokenizer() f = open(args.file) if args.ascii: text = f.read().split() arry = [] for e in text: arry.append(chr(int(e, 16))) #ascString = string.join(arry) ascString = arry else: ascString = f.read() tmp = '' for c in ascString: if ord(c) < 128: tmp = tmp + c ascString = tmp if args.cipherLen: print('cipher text length: ' + str(len(ascString))) if args.findKey: print(findKey.getNgramsDispersion(string.join(ascString), args.pLen, args.nRes)) if args.plotByAlpha > 0: alphas = split.splitByAlpha(args.plotByAlpha, ascString) g = 0 for group in alphas: g += 1 myFreqDist.MyFreqDist(group).createPlot(args.outDir + 's' + str(args.plotByAlpha) + 'g' + str(g), 10) if args.shiftByAlpha > 0: alphas = split.splitByAlpha(args.shiftByAlpha, ascString) candidate = shift.shiftByAlpha(alphas, ascString, args.common, args.reverseShift) file = open(args.outDir + 'candidate.pln', 'w') print(candidate) if args.xorByAlpha > 0: alphas = split.splitByAlpha(args.xorByAlpha, ascString) candidate = xor.xorByAlpha(alphas, ascString, args.common) file = open(args.outDir + 'candidate.pln', 'w') print(candidate) if args.grid > 0: grid.grid(ascString, args.grid) if args.perpGrid > 0: perpGrid.grid(ascString, args.perpGrid) if len(args.transpose) > 0: transpose.transpose(ascString, args.transpose)
def test_two_characters_in_a_column(self): lines = ["A", "1"] expected = ["A1"] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
def test_transpose_dict(): months, num_posts = transpose(POSTS) assert list(months) == [ '2017-8', '2017-9', '2017-10', '2017-11', '2017-12', '2018-1' ] assert list(num_posts) == [19, 13, 13, 12, 11, 3]
def test_single_line(self): lines = ["Single line."] expected = ["S", "i", "n", "g", "l", "e", " ", "l", "i", "n", "e", "."] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
def transpose(self): ans = tran.transpose(self) self.answer_field.setText(str(ans))
def test_square(self): lines = ["HEART", "EMBER", "ABUSE", "RESIN", "TREND"] expected = ["HEART", "EMBER", "ABUSE", "RESIN", "TREND"] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
def test_single_item(self): self.assertEqual(transpose([[1]]), [[1]])
def test_triangle(self): lines = ["T", "EE", "AAA", "SSSS", "EEEEE", "RRRRRR"] expected = ["TEASER", " EASER", " ASER", " SER", " ER", " R"] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))
def test_jagged_triangle(self): lines = ["11", "2", "3333", "444", "555555", "66666"] expected = ["123456", "1 3456", " 3456", " 3 56", " 56", " 5"] self.assertEqual(transpose("\n".join(lines)), "\n".join(expected))