Пример #1
0
def test_fig23_best_mask():
    # ISO/IEC 18004:2015(E) - 7.8.2 Data mask patterns
    # Figure 23
    matrix = read_matrix('fig-23-unmasked')
    masked_matrix, mask = encoder.find_best_mask(matrix, 1, is_micro=False)
    assert 0 == mask
    ref_matrix = read_matrix('fig-23-mask-0')
    assert ref_matrix == masked_matrix
Пример #2
0
def test_encode_single():
    # ISO/IEC 18004:2015(E) - page 7
    # 'QR Code Symbol' as 1-M symbol
    seq = segno.make_sequence('QR Code Symbol',
                              version=1,
                              error='M',
                              boost_error=False)
    assert '1-M' == seq.designator
    ref_matrix = read_matrix('iso-fig-1')
    assert ref_matrix == seq.matrix
    qr = seq[0]
    assert '1-M' == qr.designator
    ref_matrix = read_matrix('iso-fig-1')
    assert ref_matrix == qr.matrix
Пример #3
0
def main():
	if len(sys.argv) < 3:
		raise ValueError("Give the partitioned matrix and target file as arguments.")
	P = utils.read_matrix(sys.argv[1])
	verify.verify(P, P, debug=False)

	R, C, NZ, M = P
	F = min(10, max(1, MAX // max(R, C)))
	svg = open(sys.argv[2], 'w')
	svg.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
	svg.write(str.format('<svg xmlns:svg="http://www.w3.org/2000/svg" '
			'xmlns="http://www.w3.org/2000/svg" version="1.0" '
			'width="{}" height="{}" id="svg2">\n', C*F, R*F))

	svg.write('\t<g>\n')
	svg.write(str.format('\t\t<rect width="{}" height="{}" x="0" y="0" id="bkg" '
			 'style="fill:#ffffff;fill-opacity:1;" />\n', C*F, R*F))

	for r, row in enumerate(M):
		for c, v in row:
			svg.write(str.format(
				'\t\t\t<rect width="{}" height="{}" x="{}" y="{}" '
				'id="r{}-{}" style="fill:{};fill-opacity:1;" />\n',
				F, F, c*F, r*F, c, r, side_to_color(int(v[0]))))

	svg.write('\t</g>\n</svg>\n')
	svg.close()
Пример #4
0
def main():
    if len(sys.argv) < 3:
        raise ValueError(
            "Give the partitioned matrix and target file as arguments.")
    P = utils.read_matrix(sys.argv[1])
    verify.verify(P, P, debug=False)

    R, C, NZ, M = P
    F = min(10, max(1, MAX // max(R, C)))
    svg = open(sys.argv[2], 'w')
    svg.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
    svg.write(
        str.format(
            '<svg xmlns:svg="http://www.w3.org/2000/svg" '
            'xmlns="http://www.w3.org/2000/svg" version="1.0" '
            'width="{}" height="{}" id="svg2">\n', C * F, R * F))

    svg.write('\t<g>\n')
    svg.write(
        str.format(
            '\t\t<rect width="{}" height="{}" x="0" y="0" id="bkg" '
            'style="fill:#ffffff;fill-opacity:1;" />\n', C * F, R * F))

    for r, row in enumerate(M):
        for c, v in row:
            svg.write(
                str.format(
                    '\t\t\t<rect width="{}" height="{}" x="{}" y="{}" '
                    'id="r{}-{}" style="fill:{};fill-opacity:1;" />\n', F, F,
                    c * F, r * F, c, r, side_to_color(int(v[0]))))

    svg.write('\t</g>\n</svg>\n')
    svg.close()
Пример #5
0
def readlist(instancedir):
    files = os.listdir(instancedir)
    bestfiles_score = ['0'] * len(files)
    finalsol = open('finalsol.out', 'wb')
    bestfiles = f.read().splitlines()
    for f in files:
        if f.endswith('.in'):
            try:
                mat = utils.read_matrix(os.path.join(instancedir, f))
                filenum = f[:-3]
                length = len(mat)
                solname = 'solcheck'
                sol = open(solname, 'wb')
                sol.write(bestfiles[int(filenum)])
                sol.close()
                scorestring = scorer_single.processTest(
                    os.path.join(instancedir, f), solname)
                score = float(scorestring[18:])
                bestfiles_score[int(filenum)] = score
            except:
                raise
    finalsol_score = open('finalsol_score.out', 'wb')
    for b in bestfiles_score:
        finalsol_score.write(str(b))
        finalsol_score.write("\n")
    finalsol_score.close()


#x=readlist('/cygdrive/c/Users/sam.holladay/Downloads/phase1/instances')
Пример #6
0
def test_thonky_add_format_info():
    # <http://www.thonky.com/qr-code-tutorial/format-version-information#put-the-format-string-into-the-qr-code>
    version = 1
    matrix = encoder.make_matrix(version, reserve_regions=False)
    encoder.add_finder_patterns(matrix, is_micro=False)
    encoder.add_format_info(matrix, version, consts.ERROR_LEVEL_L, 4)
    ref_matrix = read_matrix('thonky_format')
    assert ref_matrix == matrix
Пример #7
0
def test_encode_iso_fig29():
    # ISO/IEC 18004:2015(E) - page 60
    # ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ

    #TODO: If mask is None, Segno chooses mask 3, but the figure uses mask 4...
    qr = encoder.encode('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                            error='m', mask=4, boost_error=False)
    assert qr.mask == 4
    ref_matrix = read_matrix('iso-fig-29')
    assert ref_matrix == qr.matrix
Пример #8
0
def test_thonky_add_version_info():
    # <http://www.thonky.com/qr-code-tutorial/format-version-information>
    version = 7
    matrix = encoder.make_matrix(version, reserve_regions=False)
    encoder.add_finder_patterns(matrix, is_micro=False)
    encoder.add_alignment_patterns(matrix, version)
    encoder.add_version_info(matrix, version)
    matrix[-8][8] = 0x1  # dark module
    ref_matrix = read_matrix('thonky_version')
    assert ref_matrix == matrix
Пример #9
0
def test_encode_iso_fig1():
    # ISO/IEC 18004:2015(E) - page 7
    # 'QR Code Symbol' as 1-M symbol
    qr = encoder.encode('QR Code Symbol', error='M', mask=None, micro=False,
                        boost_error=False)
    assert consts.ERROR_LEVEL_M == qr.error
    assert 1 == qr.version
    assert 5 == qr.mask, 'Wrong mask, got: {0}'.format(qr.mask)
    ref_matrix = read_matrix('iso-fig-1')
    assert ref_matrix == qr.matrix
Пример #10
0
def test_thonky_pattern_2():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-2')
    matrix_size = len(matrix)
    assert 206 == encoder.score_n1(matrix, matrix_size)
    assert 141 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 160
    assert 800 == encoder.score_n3(matrix, matrix_size)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    assert 507 - 160 + 800 == encoder.evaluate_mask(matrix, matrix_size)
Пример #11
0
def test_thonky_pattern_7():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-7')
    matrix_size = len(matrix)
    assert 197 == encoder.score_n1(matrix, matrix_size)
    assert 123 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 200
    assert 720 == encoder.score_n3(matrix, matrix_size)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    # See score 3
    assert 520 - 200 + 720 == encoder.evaluate_mask(matrix, matrix_size)
Пример #12
0
def test_thonky_pattern_3():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-3')
    matrix_size = len(matrix)
    assert 180 == encoder.score_n1(matrix, matrix_size)
    assert 141 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 120
    assert 760 == encoder.score_n3(matrix, matrix_size)
    # Thonky: 2, but that's impossible: Either 0 or a multiple of 10 (N4 = 10)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    assert 443 - 2 - 120 + 760 == encoder.evaluate_mask(matrix, matrix_size)
Пример #13
0
def test_thonky_pattern_1():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-1')
    matrix_size = len(matrix)
    assert 172 == encoder.score_n1(matrix, matrix_size)
    assert 129 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 120
    assert 760 == encoder.score_n3(matrix, matrix_size)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    # See score 3
    assert 421 - 120 + 760 == encoder.evaluate_mask(matrix, matrix_size)
Пример #14
0
def test_thonky_pattern_0():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-0')
    matrix_size = len(matrix)
    assert 180 == encoder.score_n1(matrix, matrix_size)
    assert 90 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 80
    assert 760 == encoder.score_n3(matrix, matrix_size)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    # See score 3
    assert 350 - 80 + 760 == encoder.evaluate_mask(matrix, matrix_size)
Пример #15
0
def test_format_info_figure26():
    # 7.9.2 Micro QR Code symbols (page 57)
    version = consts.VERSION_M1
    mask = 3
    matrix = tuple([bytearray([0x0] * 11) for i in range(11)])
    encoder.add_timing_pattern(matrix, is_micro=True)
    encoder.add_finder_patterns(matrix, is_micro=True)
    encoder.add_format_info(matrix, version=version, error=None, mask_pattern=mask)
    ref_matrix = read_matrix('fig-26')
    assert len(ref_matrix) == len(matrix)
    assert ref_matrix == matrix
Пример #16
0
def randsolutions(instancedir):
    files = os.listdir(instancedir)
    notopened = []
    bestfiles = ['0'] * len(files)
    bestfiles_score = ['0'] * len(files)
    for f in files:
        if f.endswith('.in'):
            try:
                mat = utils.read_matrix(os.path.join(instancedir, f))
                filenum = f[:-3]
                length = len(mat)
                randlist = range(1, length + 1)
                # Try random list 100 times
                top_score = -1
                top_score_str = ''
                randsol = []
                for i in range(150):
                    randsol = random.sample(randlist, len(randlist))
                    #reverselist = list(reversed(randlist))
                    solname = 'sol' + filenum
                    sol = open(solname, 'wb')
                    stringsol = ' '.join(map(str, randsol))
                    sol.write(stringsol)
                    sol.close()
                    scorestring = scorer_single.processTest(
                        os.path.join(instancedir, f), solname)
                    score = float(scorestring[18:])
                    if score < 0.2:
                        randsol = list(reversed(randsol))
                        score = 1 - score
                        stringsol = ' '.join(map(str, randsol))
                    if score > top_score:
                        top_score = score
                        top_score_str = stringsol
                    # Save time
                    if score > 0.92:
                        break
                bestfiles[int(filenum)] = top_score_str
                bestfiles_score[int(filenum)] = top_score
                os.remove(solname)
            # Couldn't read the input file; error with utils.read_matrix
            except:
                notopened.append(f)
    finalsol = open('finalsol.out', 'wb')
    for b in bestfiles:
        finalsol.write(b)
        finalsol.write("\n")
    finalsol.close()
    finalsol_score = open('finalsol_score.out', 'wb')
    for b in bestfiles_score:
        finalsol_score.write(str(b))
        finalsol_score.write("\n")
    finalsol_score.close()
    return notopened
Пример #17
0
def test_thonky_pattern_6():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-6')
    matrix_size = len(matrix)
    assert 171 == encoder.score_n1(matrix, matrix_size)
    assert 102 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 80
    assert 840 == encoder.score_n3(matrix, matrix_size)
    # Thonky: 4, but that's impossible: Either 0 or a multiple of 10 (N4 = 10)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    # See score 3 and 4
    assert 357 - 4 - 80 + 840 == encoder.evaluate_mask(matrix, matrix_size)
Пример #18
0
def test_thonky_pattern_5():
    # http://www.thonky.com/qr-code-tutorial/data-masking
    matrix = read_matrix('thonky_datamasking_mask-5')
    matrix_size = len(matrix)
    assert 189 == encoder.score_n1(matrix, matrix_size)
    assert 156 == encoder.score_n2(matrix, matrix_size)
    # Thonky: 200
    assert 800 == encoder.score_n3(matrix, matrix_size)
    # Thonky: 2, but that's impossible: Either 0 or a multiple of 10 (N4 = 10)
    assert 0 == encoder.score_n4(matrix, matrix_size)
    # See score 3 and 4
    assert 547 - 2 - 200 + 800 == encoder.evaluate_mask(matrix, matrix_size)
Пример #19
0
def test_encode_multi_by_version_or_symbol_count(version, symbol_count):
    # ISO/IEC 18004:2015(E) - page 60
    seq = segno.make_sequence(
        'ABCDEFGHIJKLMN'
        'OPQRSTUVWXYZ0123'
        '456789ABCDEFGHIJ'
        'KLMNOPQRSTUVWXYZ',
        version=version,
        symbol_count=symbol_count,
        error='m',
        mask=4,
        boost_error=False)
    assert 4 == len(seq)
    ref_matrix = read_matrix('seq-iso-04-01')
    assert ref_matrix == seq[0].matrix
    ref_matrix = read_matrix('seq-iso-04-02')
    assert ref_matrix == seq[1].matrix
    ref_matrix = read_matrix('seq-iso-04-03')
    assert ref_matrix == seq[2].matrix
    ref_matrix = read_matrix('seq-iso-04-04')
    assert ref_matrix == seq[3].matrix
Пример #20
0
def main():
    # all data are 2-dimensional matrix
    X = utils.read_matrix(INPUT_DIR + 'X_data.csv')
    y = utils.read_matrix(INPUT_DIR + 'y_label.csv')
    sigma = utils.read_matrix(INPUT_DIR + 'sigma_data.csv')
    beta = utils.read_matrix(INPUT_DIR + 'beta_data.csv')
    n, p = X.shape
    # for each x, compute its POSTERIOR probability of P(y|x)
    # y = 1, X ~ MVN(beta, sigma)
    # y = -1, X ~ MVN(-beta, sigma)
    prob_pos, prob_neg = prob_y_given_x(X, y, sigma, beta)
    pred = np.where(prob_pos > 0.5, 1, -1)
    pred = pred[:, np.newaxis]
    prob_pos = prob_pos[:, np.newaxis] - 0.5
    # approximate the optimal coefficients
    # prob_pos should be the score return by the classifier
    extra_col = np.ones(shape=(n, 1))
    X = np.append(X, extra_col, axis=1)
    # solve least square solution for Xw = prob_pos
    w, *_ = lsqr(X, prob_pos)
    print(w)
    np.savetxt('./var/optimal_w.csv', w, delimiter=',')
Пример #21
0
def test_figure22_mask3():
    # ISO/IEC 18004:2015(E) - 7.8.2 Data mask patterns
    # Figure 22 - Mask 3
    version = consts.VERSION_M4
    matrix = _make_figure22_matrix()
    matrix, mask = encoder.find_best_mask(matrix, version, True, proposed_mask=3)
    # Format info = dark modules
    for i in range(9):
        matrix[8][i] = 0x1
        matrix[i][8] = 0x1
    ref_matrix = read_matrix('fig-22-mask-3')
    assert len(ref_matrix) == len(matrix)
    assert ref_matrix == matrix
Пример #22
0
def test_codeword_placement_iso_i3():
    # ISO/IEC 18004:2015(E) - page 96
    # 01234567 as M2-L symbol
    s = '01000000 00011000 10101100 11000011 00000000'
    codewords = Buffer(bits(s)).toints()
    version = consts.VERSION_M2
    buff = encoder.make_final_message(version, consts.ERROR_LEVEL_L, codewords)
    expected_s = '01000000 00011000 10101100 11000011 00000000 10000110 00001101 00100010 10101110 00110000'
    expected = bits(expected_s)
    assert expected == buff.getbits()
    matrix = encoder.make_matrix(version)
    encoder.add_finder_patterns(matrix, is_micro=version < 1)
    encoder.add_codewords(matrix, buff, version=version)
    ref_matrix = read_matrix('iso-i3_code_placement')
    assert ref_matrix == matrix
Пример #23
0
def test_encode_iso_i3():
    # ISO/IEC 18004:2015(E) - page 96
    # 01234567 as M2-L symbol
    qr = encoder.encode('01234567', error='l', version='m2', mask=1, micro=True,
                        boost_error=False)
    assert consts.ERROR_LEVEL_L == qr.error
    assert consts.VERSION_M2 == qr.version
    assert 1 == qr.mask, 'Wrong mask, got: {0}'.format(qr.mask)
    qr = encoder.encode('01234567', error='l', version=None, mask=1, micro=True,
                        boost_error=False)
    assert consts.ERROR_LEVEL_L == qr.error
    assert consts.VERSION_M2 == qr.version
    assert 1 == qr.mask, 'Wrong mask, got: {0}'.format(qr.mask)
    ref_matrix = read_matrix('iso-i3')
    assert ref_matrix == qr.matrix
Пример #24
0
def test_encode_iso_i2():
    # ISO/IEC 18004:2015(E) - page 94
    # 01234567 as 1-M symbol
    #TODO: Without the mask param Segno chooses mask 3 which seems to be correct
    # Mask 2 is IMO an error in the standard
    qr = encoder.encode('01234567', error='m', version=1, mask=2, micro=False,
                        boost_error=False)
    assert consts.ERROR_LEVEL_M == qr.error
    assert 1 == qr.version
    assert 2 == qr.mask, 'Wrong mask, got: {0}'.format(qr.mask)
    qr = encoder.encode('01234567', error='m', mask=2, micro=False,
                        boost_error=False)
    assert consts.ERROR_LEVEL_M == qr.error
    assert 1 == qr.version
    assert 2 == qr.mask, 'Wrong mask, got: {0}'.format(qr.mask)
    ref_matrix = read_matrix('iso-i2')
    assert ref_matrix == qr.matrix
Пример #25
0
def solve(file):
    if file.endswith('.in'):
        mat = utils.read_matrix(file)
        sccmaker = SCCMaker.SCCMaker(mat)
        sccDag = sccmaker.Kosarajus()
        sorted = functions.topological_sort(sccDag)
        solutionlist = []
        if(sorted is None):
            sorted = sccDag
        for s in sorted:
            ordering = functions.efficient_cycle_main(s, mat)[1]
            solutionlist.extend(ordering)
        filenum = file[:-3]
        solname='solcheck'
        sol = open(solname, 'wb')
        stringsol = ' '.join(map(str,solutionlist))
        sol.write(stringsol.encode('utf-8'))
        sol.close()
        scorestring = scorer_single.processTest(file, solname)
        return (stringsol, scorestring)
Пример #26
0
def main():
	if len(sys.argv) < 3:
		raise ValueError("Give the original and partitioned matrices as arguments.")
	O, P = utils.read_matrix(sys.argv[1]), utils.read_matrix(sys.argv[2])
	verify(O, P)