def run(x, y, z, num_lines=0, max_retry=1, basename=None): """ 指定されたサイズ、線数の問題データと正解データを自動生成して、ファイルbasename*.txtに書き出す。 @param x,y,z 盤のサイズ @param num_lines 線の本数 @param basename 出力先ファイル名。問題ファイルはbasename_adc.txt、正解ファイルはbasename_adc_sol.txtになる。 """ Q = {'size': (x, y, z)} num_lines, ban = generate(x, y, z, num_lines=num_lines, max_retry=max_retry, Q_data=Q) Q['line_num'] = num_lines Q['empty_cells'] = ban.empty_cells() print('number of lines:', Q['line_num']) print('number of empty cells:', Q['empty_cells']) #if verbose: ban.print() #if verbose: print('Q=', Q) txtQ = Q_text(Q) txtA = ban.A_data() # nlcheckする nlc = NLCheck() q = nlc.read_input_str(txtQ) a = nlc.read_target_str(txtA) #nlc.verbose = verbose judges = nlc.check(q, a) print("judges = ", judges) # 描画する nldraw2.setup_font('nonexistent') # あとで考える images = nldraw2.draw(q, a, nlc) for num, img in enumerate(images): ifile = "%s.%d.gif" % (basename, num + 1) # 層の番号は1から始まる img.save(ifile, 'gif') print(ifile) if 1 < len(images): nldraw2.merge_images(images).save(basename + '.gif', 'gif') # QとAを出力する if basename is None: print(txtQ) print(txtA) else: qfile = '%s_adc.txt' % basename with open(qfile, 'w') as f: f.write(txtQ) afile = '%s_adc_sol.txt' % basename with open(afile, 'w') as f: f.write(txtA) excel(ban, basename)
def check_A_data(a_text, q_text): """回答データのチェックをする""" nlc = NLCheck() #nlc.debug = True #print "Q=",q_text #print "A=",a_text out = io.BytesIO() # io.StringIO()だとTypeError: unicode argument expected, got 'str' #out = open("/tmp/nlcheck_log.txt","w") #-------------------------------------- sys.stdout = out # 標準出力を付け替える input_data = nlc.read_input_str(q_text) # 問題データ target_data = nlc.read_target_str(a_text) # 回答データ nlc.verbose = True judges = nlc.check(input_data, target_data) print "judges = ", judges #results = escape(out.getvalue()) # from xml.sax.saxutils import escape, unescape ここでは不要か?! msg = out.getvalue() out.close() sys.stdout = sys.__stdout__ # もとに戻す #-------------------------------------- return judges, msg
def read_input_data(text): nlc = NLCheck() ok = True msg = "" #-------------------------------------- out = io.BytesIO( ) # io.StringIO()だとTypeError: unicode argument expected, got 'str' backup_stdout = sys.stdout sys.stdout = out # 標準出力を付け替える ret = None try: ret = nlc.read_input_str(text) except: ok = False ret = (None, None, None, None, None) size, line_num, line_mat, via_mat, via_dic = ret msg = out.getvalue() out.close() sys.stdout = backup_stdout # もとに戻す #-------------------------------------- if "ERROR" in msg: ok = False print msg return (size, line_num, line_mat, via_mat, via_dic, msg, ok)
def main(): qfile, afile = sys.argv[1:] afile = sys.argv[2] print qfile,afile nlc = NLCheck() q = nlc.read_input_file(qfile) a = nlc.read_target_file(afile) #print "q=",q #print "a=",a #a = nlc.clean_a(q, a) # 回答をチェックする nlc.verbose = True judges = nlc.check( q, a ) print "judges = ", judges # 描画する images = draw(q,a,nlc) bfile = basename(qfile) bfile = re.sub("\.txt", "", bfile) num = 0 for img in images: ifile = "%s.%d.gif" % (bfile, num) img.writeGif(ifile) print ifile num += 1
def main(): global ttf_font, font_size, unit import argparse parser = argparse.ArgumentParser(description='NumberLink check and drawing tool') parser.add_argument('-f', '--font', default=ttf_font, help='TrueType font file (default: %(default)s)') parser.add_argument('--font-size', metavar='N', type=int, default=font_size, help='font size (default: %(default)s)') parser.add_argument('--unit', metavar='N', type=int, default=unit, help='unit square size (default: %(default)s)') parser.add_argument('--test', action='store_true', help='test GIF output') parser.add_argument('qfile', metavar='Q-FILE', help='input file (Q-file)') parser.add_argument('afile', metavar='A-FILE', help='target file (A-file)') args = parser.parse_args() ttf_font = args.font font_size = args.font_size unit = args.unit setup_font(ttf_font) if args.test: test() qfile = args.qfile afile = args.afile print(qfile, afile) nlc = NLCheck() q = nlc.read_input_file(qfile) a = nlc.read_target_file(afile) #print("q=",q) #print("a=",a) #a = nlc.clean_a(q, a) # 回答をチェックする nlc.verbose = True judges = nlc.check( q, a ) print("judges = ", judges) # 描画する images = draw(q, a, nlc) bfile = os.path.basename(qfile) bfile = os.path.splitext(bfile)[0] # 拡張子をトル for num, img in enumerate(images): ifile = "%s.%d.gif" % (bfile, num+1) # 層の番号は1から始まる img.save(ifile, 'gif') print(ifile) if 1 < len(images): merge_images(images).save(bfile+'.gif', 'gif')
def check_A_data(a_str, q_uni): """回答データのチェックをする""" # 問題データ q_uni (unicode) # 回答データ a_str (str) nlc = NLCheck() #nlc.debug = True q_str = q_uni.encode('utf-8') # unicode -> str #print "Q=",q_str #print "A=",a_str #-------------------------------------- out = io.BytesIO( ) # io.StringIO()だとTypeError: unicode argument expected, got 'str' sys.stdout = out # 標準出力を付け替える input_data = nlc.read_input_str(q_str) target_data = nlc.read_target_str(a_str) nlc.verbose = True judges = nlc.check(input_data, target_data) print "judges = ", judges #results = escape(out.getvalue()) # from xml.sax.saxutils import escape, unescape ここでは不要か?! msg = out.getvalue() out.close() sys.stdout = sys.__stdout__ # もとに戻す #-------------------------------------- return judges, msg
def main(): qfile, afile = sys.argv[1:] afile = sys.argv[2] print qfile, afile nlc = NLCheck() q = nlc.read_input_file(qfile) a = nlc.read_target_file(afile) #print "q=",q #print "a=",a #a = nlc.clean_a(q, a) # 回答をチェックする nlc.verbose = True judges = nlc.check(q, a) print "judges = ", judges # 描画する images = draw(q, a, nlc) bfile = basename(qfile) bfile = re.sub("\.txt", "", bfile) num = 0 for img in images: ifile = "%s.%d.gif" % (bfile, num) img.writeGif(ifile) print ifile num += 1
def solve(num): global project_dir o = NLCheck() output_info = info['output_info'][num] via_to_line = get_via_to_line(info, num) adata = 'SIZE %dX%dX%d\r\n' % info['size'] fail = False cwd = os.getcwd() #--------------------------------------- os.chdir(project_dir) for layer, info2 in sorted(output_info.items()): if layer[0] != 'L' or not layer[1:].isdigit(): continue qfile = info2['ofile'] afile = exec_solver(qfile) #print layer, qfile, afile input_data = o.read_input_file(qfile) target_data = o.read_target_file(afile) target_data2 = o.clean_a(input_data, target_data) judges = o.check(input_data, target_data2) best = best_target(judges) print "judges = ", judges print "best = ", best #print "best target_data = ", target_data2[best[0]] ilayer = int(layer[1:]) # 1,2,… via_linenum = get_via_linenum_mat(info, ilayer, via_to_line) adata += 'LAYER %d\r\n' % ilayer if best[0] is None: fail = True break else: bd = target_data2[best[0]] adata += generate_A_data(bd, info2['map_line_num'], via_linenum) if 0: root, ext = os.path.splitext(afile) gfile = root + '.gif' gif = o.graphic_gif(input_data, [bd], gfile) print "gif = ", gif os.chdir(cwd) #--------------------------------------- if fail: output_info['judges'] = None return None else: # afile: 2016年版ルールの回答ファイルの名前 root, ext = os.path.splitext(os.path.basename(info['convert_q'])) afile = root + ('.%d.A.txt' % num) afile2 = os.path.join(project_dir, afile) with open(afile2, 'w') as fp: fp.write(adata) # 2016年版ルールで回答チェック input_data = o.read_input_file(info['convert_q']) target_data = o.read_target_str(adata) judges = o.check(input_data, target_data) print "afile = ", afile print "judges = ", judges output_info['afile'] = afile output_info['judges'] = judges if judges[0][0]: # 正解が出た gfile = root + ('.%d.A.gif' % num) gfile2 = os.path.join(project_dir, gfile) gif = o.graphic_gif(input_data, target_data, gfile2) print "gif = ", gif return afile
def convert(qfile, candidates=None): "2016年版ルールの問題ファイルを、変換する" o = NLCheck() res = o.read_input_file(qfile) if debug: label = ['size', 'line_num', 'line_mat', 'via_mat', 'via_dic'] for i in range(0, 5): print label[i], '=\n', res[i] size, org_line_num, line_mat, via_mat, via_dic = res layer_num = size[2] qs = [] found_linevia = {} for layer in range(1, layer_num + 1): line_num1 = 0 line_num2 = 0 lineinfo = [] linevia = [] # このlayerで、線とviaがつながっている for line in line_mat: line_num1 += 1 if line[2] == line[5] and line[2] == layer: # 1つのレイヤー内で完結している線 line_num2 += 1 lineinfo.append({ 'LINE#': line_num1, 'pos0': (line[0], line[1]), 'pos1': (line[3], line[4]) }) elif line[2] == layer: line_num2 += 1 lineinfo.append({ 'LINE#': line_num1, 'pos0': (line[0], line[1]), 'pos1': None }) linevia.append(line_num1) found_linevia[line_num1] = True elif line[5] == layer: line_num2 += 1 lineinfo.append({ 'LINE#': line_num1, 'pos0': (line[3], line[4]), 'pos1': None }) linevia.append(line_num1) found_linevia[line_num1] = True qs.append({ 'SIZE': (size[0], size[1]), 'LINE_NUM': line_num2, 'LINE': lineinfo, 'linevia': linevia }) #print qs #print "qs[0]['LINE']=\n", qs[0]['LINE'] #print "qs[1]['LINE']=\n", qs[1]['LINE'] global_linevia = sorted(found_linevia) if debug: print "global_linevia=", global_linevia # エラーチェック: すべてのlayerで、lineviaは一致する ★それは2層の場合だけ #for layer in range(1, layer_num): # #print "qs[%d]['linevia']=" % (layer-1), qs[layer-1]['linevia'] # #print "qs[%d]['linevia']=" % (layer), qs[layer]['linevia'] # if qs[layer-1]['linevia'] != qs[layer]['linevia']: # print "Error in via: layer %d and %d" % (layer, layer+1) # if len(via_dic) != len(qs[layer-1]['linevia']): # print "Error in number of via: layer %d" % layer # ★3層以上の場合を考慮 # エラーチェック: 数字マスはviaを経由してつながっている # = 対となるlineviaがあるはず # = 2回ずつ出現するはず count_linevia = {} for layer in range(1, layer_num + 1): for n in qs[layer - 1]['linevia']: if n in count_linevia: count_linevia[n] += 1 else: count_linevia[n] = 1 if debug: print "count_linevia=", count_linevia for n in global_linevia: if count_linevia[n] != 2: print "Error: please check connection between line#%d and via" vias = sorted(via_dic.keys()) if candidates is None: candidates = [] assign_via_line(vias, [], candidates) info['size'] = size # layer_numは、size[2] info['org_line_num'] = org_line_num info['line_mat'] = line_mat info['via_mat'] = via_mat info['via_dic'] = via_dic info['qs'] = qs info['vias'] = vias info['global_linevia'] = global_linevia info['candidates'] = candidates info['output_info'] = [None] * (1 + len(candidates)) idx = 0 for c in candidates: info['output_info'][idx] = output_q(global_linevia, org_line_num, qs, c, via_mat, via_dic, qfile, idx) idx += 1
#!/usr/bin/env python # -*- coding: utf-8 ; mode: python -*- # # Aファイルを読み込んで、空白マスの割合を計算する # # # 実行例 ./space.py ../../ADC2015_QA/A/*txt import os, sys, re sys.path.insert(1, '../server') from nlcheck import NLCheck nlc = NLCheck() pat = re.compile('(.*)_A([0-9]+)\.txt') print "user,A,area,zeros,rate" for file in sys.argv[1:]: res = nlc.read_target_file(file) for i in res: y, x = i.shape area = y * x nzeros = len(i[i == 0]) # 値が0の個数 rate = float(nzeros) / (float(area)) f1 = os.path.basename(file) m = pat.match(f1) user = '******' anum = '?' if m is not None: user = m.group(1)
#!/usr/bin/env python # -*- coding: utf-8 ; mode: python -*- # # Aファイルを読み込んで、空白マスの割合を計算する # # # 実行例 ./space.py ../../ADC2015_QA/A/*txt import os, sys, re sys.path.insert(1, '../server') from nlcheck import NLCheck nlc = NLCheck() pat = re.compile('(.*)_A([0-9]+)\.txt') print "user,A,area,zeros,rate" for file in sys.argv[1:]: res = nlc.read_target_file(file) for i in res: y,x = i.shape area = y*x nzeros = len(i[i==0]) # 値が0の個数 rate = float(nzeros) / (float(area)) f1 = os.path.basename(file) m = pat.match(f1) user = '******' anum = '?' if m is not None: user = m.group(1)