Beispiel #1
0
    def calc_with_Fraction(self):
        def process_operation(operation):
            r_operand = operands[-1]
            operands.pop()
            if operation[0] == 'u':
                if operation == 'u-':
                    operands.append(-r_operand)
                if operation == 'u+':
                    operands.append(r_operand)
            else:
                l_operand = operands[-1]
                operands.pop()
                if operation == '+':
                    operands.append(l_operand + r_operand)
                if operation == '-':
                    operands.append(l_operand - r_operand)
                if operation == '*':
                    operands.append(l_operand * r_operand)
                if operation == '/':
                    operands.append(l_operand / r_operand)

        operands = list()
        for element in self.polish_notation_list:
            if RPN.is_operation(element):
                process_operation(element)
            else:
                if element.isalpha():
                    operands.append(Fraction({element: 1}))
                else:
                    operands.append(Fraction({'1': float(element)}))
        return operands[-1]
Beispiel #2
0
    def test_ne(self):
        f1 = Fraction(1, 2)
        f2 = Fraction(1, 2)
        f3 = Fraction(1, 3)

        self.assertTrue(f1 != f3)
        self.assertFalse(f1 != f2)
Beispiel #3
0
 def canPlay(self, alavu, diff):
     # This function tells whether we can play a the Korvai of alavu
     # mathirai. Also the difference can be anything. i.e. If
     # self.nadai = [ 3, 3, 4] and the parameter diff = 0,
     # and alavu = 1, then we know that it is not possible to play the
     # korvai of 1 Mathirai in this pattern of nadai
     # if alavu = 3, we can play and we return true. The function checks
     # for the criteria on which alavu and diff is possible.
     assert isinstance(alavu, int)
     if isinstance(diff, int):
         diff = itertools.repeat(diff)
     _alavu = alavu
     total = Fraction(0, 1)
     for group, d in zip(self.nadais, diff):
         for nadai in group:
             # Check whether we can start nadai at this place
             if not self.can_start(total, nadai):
                 return None
             total = total + Fraction(_alavu, nadai)
         _alavu = _alavu + d
     if (self.can_start(total, 4)):
         tot = (total * 4)
         assert (tot.getD() == 1)
         return SetTot(alavu, tot.getN())
     else:
         return None
Beispiel #4
0
def Zero(n):
    k = 0
    total = Fraction(k, 1)
    for x in range(k, n + 1):
        i = (Fraction(1, 2)**x)
        total += i
    return Fraction(2, 1) - total
Beispiel #5
0
    def test_mult(self):
        f1 = Fraction(1, 2)
        f2 = Fraction(1, 4)
        f3 = f1 * f2

        self.assertEqual(f3.get_num(), 1)
        self.assertEqual(f3.get_den(), 8)
    def test_when_fractions_have_gcd_denominators_non_equal_to_1(self):
        fraction1 = Fraction(3, 2)
        fraction2 = Fraction(5, 10)
        result = fraction1 + fraction2  # 2/1

        self.assertEqual(result.numerator, 2)
        self.assertEqual(result.denominator, 1)
Beispiel #7
0
    def get_roots(self):
        roots_list = []

        c0 = self.coefficients[len(self.coefficients) - 1]
        c0_divisors = []

        for i in range(1, int(sqrt(abs(c0))) + 2):
            if c0 % i == 0:
                c0_divisors.append(i)

        cn = self.coefficients[0]
        cn_divisors = []

        for i in range(1, int(sqrt(abs(cn))) + 2):
            if cn % i == 0:
                cn_divisors.append(i)

        for numerator in c0_divisors:
            for denominator in cn_divisors:
                self.x = Fraction(numerator, denominator)

                if self.get_value().fraction_numerator == 0:
                    roots_list.append(Fraction(numerator, denominator))

        if not roots_list:
            return 0

        return roots_list
Beispiel #8
0
def H(n):
    frac = Fraction(1, 1)
    k = 2
    while k <= n:
        frac = frac + Fraction(1, k)
        k += 1
    return frac
 def test_eq(self):
     f = Fraction(1,2)
     g = Fraction(-40,-80)
     h = Fraction(10000,20001)
     self.assertTrue(f==g)
     self.assertTrue(f.__eq__(g))
     
Beispiel #10
0
def Z(n):
    frac = Fraction(1, 1)
    k = 1
    while k <= n:
        frac = frac + (Fraction(1, 2)**k)
        k += 1
    return Fraction(2, 1) - frac
Beispiel #11
0
def R(n, b):
    frac = Fraction(1, 1)
    k = 2
    while k <= n:
        frac = frac + (Fraction(1, k)**b)
        k += 1
    return frac
Beispiel #12
0
def T(n):
    frac = Fraction(1, 1)
    k = 1
    while k <= n:
        frac = frac + (Fraction(1, 2)**k)
        k += 1
    return frac
Beispiel #13
0
 def test_init(self):
     with self.assertRaises(TypeError):
         Fraction("hi", 3)
     with self.assertRaises(TypeError):
         Fraction(2, "Hello")
     with self.assertRaises(TypeError):
         Fraction("bear", "wolf")
Beispiel #14
0
 def test_not_a_int(self):
     with self.assertRaises(TypeError):
         Fraction([1,2,3])
     with self.assertRaises(TypeError):
         Fraction({})
     with self.assertRaises(TypeError):
         Fraction("Hello")
Beispiel #15
0
 def test_init(self):
     a = Fraction(2, 4)
     self.assertEqual(1, a.numerator)
     self.assertEqual(2, a.denominator)
     b = Fraction(-3, 9)
     self.assertEqual(-1, b.numerator)
     self.assertEqual(3, b.denominator)
     c = Fraction(4, -2)
     self.assertEqual(-2, c.numerator)
     self.assertEqual(1, c.denominator)
     d = Fraction(-800, -200)
     self.assertEqual(4, d.numerator)
     self.assertEqual(1, d.denominator)
     e = Fraction(-4)
     self.assertEqual(-4, e.numerator)
     self.assertEqual(1, e.denominator)
     g = Fraction(5)
     self.assertEqual(5, g.numerator)
     self.assertEqual(1, g.denominator)
     h = Fraction(0, 1)
     self.assertEqual(0, h.numerator)
     self.assertEqual(1, h.denominator)
     i = Fraction(-1, 0)
     self.assertEqual(-1, i.numerator)
     self.assertEqual(0, i.denominator)
     j = Fraction(-3, 0)
     self.assertEqual(-1, j.numerator)
     self.assertEqual(0, j.denominator)
     k = Fraction(0, 0)
     self.assertEqual(0, k.numerator)
     self.assertEqual(0, k.denominator)
def test_divide():
    """ """
    f1 = Fraction(5, 8)
    f2 = Fraction(1, 1)
    f3 = f1 / f2
    assert f3.__str__() != "5/8"
    assert f3.as_decimal == 0.625
    def test_when_numerator_equals_denominator_then_return_1(self):
        fraction = Fraction(19, 19)

        simplified_fraction = fraction.simplify()

        self.assertEqual(simplified_fraction.numerator, 1)
        self.assertEqual(simplified_fraction.denominator, 1)
def test_multiply():
    """ """
    f1 = Fraction(5, 8)
    f2 = Fraction(2 / 1)
    f3 = f1 * f2
    assert f3.__str__() != "10/8"
    assert f3.as_decimal == 1.25
Beispiel #19
0
    def test_add(self):
        f1 = Fraction(1, 2)
        f2 = Fraction(3, 4)
        f3 = f1 + f2

        self.assertEqual(f3.get_num(), 5)
        self.assertEqual(f3.get_den(), 4)
Beispiel #20
0
    def test_div_two_fractions(self):
        f1 = Fraction(1, 3)
        f2 = Fraction(1, 2)
        f3 = f1 / f2

        self.assertEqual(f3.num, 2)
        self.assertEqual(f3.den, 3)
Beispiel #21
0
def T(n):
    t = Fraction(0, 1)
    k = 0
    while (k <= n):
        t += Fraction(1, 2)**k
        k += 1
    return t
Beispiel #22
0
    def test_mul_two_fractions(self):
        f1 = Fraction(2, 3)
        f2 = Fraction(1, 2)
        f3 = f1 * f2

        self.assertEqual(f3.num, 1)
        self.assertEqual(f3.den, 3)
Beispiel #23
0
 def test_sub(self):
     num4 = self.num1 - self.num2
     num5 = self.num3 - self.num1
     num6 = self.num2 - self.num3
     self.assertEqual(num4, Fraction(0, 1))
     self.assertEqual(num5, Fraction(-1, 6))
     self.assertEqual(num6, Fraction(1, 6))
Beispiel #24
0
    def test_sub_two_fractions(self):
        f1 = Fraction(1, 2)
        f2 = Fraction(1, 3)
        f3 = f1 - f2

        self.assertEqual(f3.num, 1)
        self.assertEqual(f3.den, 6)
Beispiel #25
0
    def test_div(self):
        f1 = Fraction(1, 2)
        f2 = Fraction(1, 4)
        f3 = f1 / f2

        self.assertEqual(f3.get_num(), 2)
        self.assertEqual(f3.get_den(), 1)
Beispiel #26
0
    def test_sub(self):
        f1 = Fraction(1, 2)
        f2 = Fraction(1, 4)
        f3 = f1 - f2

        self.assertEqual(f3.get_num(), 1)
        self.assertEqual(f3.get_den(), 4)
Beispiel #27
0
def classify(pieceList):
    for piece in pieceList:
        if isFractionBar(piece):
            fracbar = Fraction(piece.width, piece.height, piece.centre)
            above, below = getAboveBelow(fracbar, pieceList)
            fracbar.numerator = classify(above)
            fracbar.denominator = classify(below)
    symlist = []
    for piece in pieceList:
        if not isFractionBar(piece):
            symbol = recognise(piece)  #maybe not??????????
            symlist.append(symbol)

    tree = Tree()
    superscriptList = []
    subscriptList = []
    parentList = []

    for sym in symlist:
        if isSuperscript(sym, symlist):
            parent = findSuperscriptParent(sym, symlist)
            superscriptList.append((sym, parent))
        elif isSubscript(sym, symlist):
            parent = findSubscriptParent(sym, symlist)
            subscriptList.append((sym, parent))
        else:
            t = Tree(data=sym)
            tree.children.append(t)
            parentList.append(sym)

    # for (sym,parent) in superscriptList:
    # 	tree.findById(parent.id).children.append(sym)
    # for (sym,parent) in subscriptList:
    # 	tree.findById(parent.id).children.append(sym)

    for parent in parentList:
        superscript = []
        for (sym, p) in superscriptList:
            if p == parent:
                superscript.append(sym)
        if len(superscript) > 0:
            t = Tree()
            t.data = "superscript"  #TODO make good lol
            t.children.append(classify(superscript))
            parent.children.append(t)

        subscript = []
        for (sym, p) in subscriptList:
            if p == parent:
                subscript.append(sym)
        if len(subscript) > 0:
            t = Tree()
            t.data = "subscript"  #TODO make good lol
            t.children.append(classify(subscript))
            parent.children.append(t)

        tree.children.append(Tree(data=parent))

    return tree
Beispiel #28
0
def partialRiemannZeta(n, b):
    total = Fraction(0, 1)

    for i in range(1, n + 1):
        fraction = Fraction(1, i)**b
        total = total + fraction

    return total
Beispiel #29
0
 def testArithmetic(self):
     half = Fraction(1, 2)
     third = Fraction(1, 3)
     quarter = Fraction(1, 4)
     self.assertEqual(half + quarter, Fraction(3, 4))
     self.assertEqual(half - quarter, quarter)
     self.assertEqual(half * half, quarter)
     self.assertEqual(half / third, Fraction(3, 2))
def test_subtract():
    """Test the addition function"""
    f1 = Fraction(1, 2)
    f2 = Fraction(2, 1)

    total = f1 / f2
    assert total.__str__() == "1/4"
    assert total.as_decimal == 0.25
 def makeFraction(e):
     #reference for possibleX/Y. See actual value at beginning of class
     #possibleX = [0,1,2,3,5,7,9,11,13,17,19,23]
     #possibleY = [1,2,3,5,7,9,11,13,17,19,23]
     simpX = -1
     simpY = -1
     unSimpX = -1
     unSimpY = -1
     if (e.level == 1):
         theFactor = random.randint(2,5)
         unSimpX = 1 * theFactor
         unSimpY = random.randint(1,5) * theFactor
     elif (e.level == 2):
         theFactor = random.randint(3,7)
         unSimpX = random.randint(1,2) * theFactor
         unSimpY =  e.possibleY[random.randint(2,4)] * theFactor
     elif (e.level == 3):
         theFactor = random.randint(7,12)
         unSimpX =  random.randint(1,7) * theFactor
         unSimpY =  random.randint(2,10) * theFactor
     #create Fraction
     theFraction = Fraction()
     theFraction.theFactor = theFactor
     theFraction.unSimpX = unSimpX
     theFraction.unSimpY = unSimpY
     theFraction.gcd = gcd(theFraction.unSimpX, theFraction.unSimpY)
     theFraction.ansX = theFraction.unSimpX / theFraction.gcd
     theFraction.ansY = theFraction.unSimpY / theFraction.gcd
     return theFraction
Beispiel #32
0
def valid_m(M, bad_a, bad_b, row = 1):
    if row == 5:
        #net spoilage in A / net spoilage in B
        f = Fraction(bad_a, tot_a) / Fraction(bad_b, tot_b)
        return f == M

    #easy early termination test
    if Fraction(ca[row] + bad_a, tot_a) < M * Fraction(bad_b, tot_b):
        return False

    rate_a = Fraction(a[row], b[row]) / M
    rate_a.reduce()
    for i in range(rate_a.denom, b[row]+1, rate_a.denom):
        ct = rate_a * i
        assert ct.whole()
        if valid_m(M, bad_a + ct.int(), bad_b + i, row + 1):
            return True
    
    return False
def evaluate(fraction, inputString):
    ''' evaluate the value of a string '''
    storeValue = fraction     # the value held by the calculator
    storeOp = None
    inputItem = inputString.split()
   
    for i in range(len(inputItem)):
        currentItem = inputItem[i]
        if attribute(currentItem) is 'clear':
            # reset everything
            storeValue = Fraction(0, 1)
            storeOp = None
        elif attribute(currentItem) is 'EOF':
            raise EOFError
        elif attribute(currentItem) is 'error':
            raise ValueError
        elif attribute(currentItem) is 'value':
            if storeOp == None:
                # no operation, renew the value
                storeValue = setFraction(currentItem)
            else:
                # has operation, calculate it and forget the operation
                storeValue = setOperation(storeValue, 
                                          storeOp, 
                                          setFraction(currentItem))
                storeOp = None
        elif attribute(currentItem) is 'operator':
            if storeOp == None:
                # store the operation
                storeOp = currentItem
            else:
                # double operation
                raise ValueError
        elif attribute(currentItem) is 'abs':
            storeValue = storeValue.absValue()
        elif attribute(currentItem) is 'negate':
            storeValue = storeValue.negate()

    return storeValue
Beispiel #34
0
 def test_get_reduced_6_9(self):
     original_fraction = Fraction(6, 9)
     reduced_fraction = original_fraction.get_reduced()
     correct_reduced_fraction = Fraction(2, 3)
     self.assertEqual(correct_reduced_fraction, reduced_fraction)
     return
Beispiel #35
0
def xml_to_abc(filename):
    global default_len
    if os.path.splitext(filename)[1].lower() == '.mxl':
        root = ElementTree().parse(mxl_to_xml(filename))
    else:
        root = ElementTree().parse(filename)        
    debug = False
    results_for_different_L_fields = []

    for L in [Fraction(1, 8), Fraction(1, 16)]:
        default_len = L
        tune_fields = []
        parts = []

        if root.findtext('work/work-title', ''):
            tune_fields.append(Field('T', root.findtext('work/work-title', '').strip()))
        if root.findtext('movement-title', ''):
            tune_fields.append(Field('T', root.findtext('movement-title', '').strip()))        
        for credit in root.findall('credit'):
            credits = ''.join(e.text or '' for e in credit.findall('credit-words'))

            # ran into issues with Unicode strings, so except TypeError to avoid processing these strings
            try:
                credits = credits.translate(None, '\r\n')
                if credits.strip():
                    tune_fields.append(Field('T', credits))
            except TypeError: pass
        for creator in root.findall('identification/creator'):
            if creator.get('type') == 'composer':
                for line in creator.text.split('\n'):
                    tune_fields.append(Field('S', line.strip()))
            elif creator.get('type') == 'lyricist':
                text = creator.text
                for line in text.split('\n'):
                    tune_fields.append(Field('Z', line.strip()))

        num_parts = len(list(root.findall('part')))

        for part_no, part in enumerate(root.findall('part')):            
            accidentals = defaultdict(lambda: 0)
            measure_accidentals = accidentals
            cur_divisions = 768    
            bar_number = 0
            bar_offset = 0            

            lyric_numbers = sorted(set(lyric.get('number', '1') for lyric in part.findall('*/note/lyric')))
            lyrics = dict((lyric_number, []) for lyric_number in lyric_numbers)
            
            voice_names = sorted([voice.text for voice in part.findall('measure/note/voice')])
            if voice_names:
                first_voice = voice_names[0]
            else:
                first_voice = None
            voices = defaultdict(list)            
                
            num_staves = int(root.findtext('part/measure/attributes/staves', '1'))    
            for measure in part.findall('measure'):
                bar_number += 1
                bar_offset = 0
                last_measure_accidentals = measure_accidentals
                measure_accidentals = accidentals.copy()
                notes_with_accidentals_in_this_measure = set()                                
                
                for measure_element in measure.getchildren():        

                    # fields        
                    if measure_element.tag == 'attributes':
                        attributes = measure_element
                        for element in attributes.getiterator():
                            if element.tag == 'key':
                                # determine modal scale
                                mode, base_note_distance = key_mode_map.get(element.findtext('mode'), '')
                                
                                # insert new key in all voices
                                fifths = int(element.findtext('fifths'))
                                key_name = get_key_name(fifths, base_note_distance) + mode
                                field = Field('K', key_name)
                                if voices:
                                    for voice in voices.values():
                                        voice.append(field)
                                elif part_no == 0:                                    
                                    tune_fields.append(field)
                                    
                                # update accidentals
                                accidentals = get_accidentals(fifths)
                                measure_accidentals = accidentals.copy()
                                
                            elif element.tag == 'time':
                                metre = '%s/%s' % (element.findtext('beats'), element.findtext('beat-type'))
                                field = Field('M', metre)
                                if voices:
                                    for voice in voices.values():
                                        voice.append(field)
                                elif part_no == 0:
                                    tune_fields.append(field)                            
                                    
                            elif element.tag == 'divisions':
                                cur_divisions = int(element.text)

                    # notes                    
                    elif measure_element.tag == 'note':
                        note = measure_element
                        voice = note.findtext('voice')                        
                        
                        # name
                        if note.get('print-object') == 'no':
                            note_name = 'x'
                        elif note.find('rest') is not None:                  
                            note_name = 'z'
                        else:
                            if note.findtext('pitch/step') != None and note.findtext('pitch/octave') != None:
                                note_name = note.findtext('pitch/step') + note.findtext('pitch/octave')
                            else: note_name = "?"

                        # duration and whether it's a grace note
                        is_grace_note = note.find('grace') is not None                
                        grace_slash = False
                        if is_grace_note:
                            duration = name2duration[note.findtext('type')]
                            grace_slash = note.find('grace').get('slash') == 'yes'                    
                        else:
                            duration = Fraction(int(note.findtext('duration')), cur_divisions) / 4
                            duration.reduce()

                        # find any time-modifications (due to tuplets) and rescale displayed duration accordingly
                        actual_notes = note.findtext('time-modification/actual-notes')
                        normal_notes = note.findtext('time-modification/normal-notes')
                        if actual_notes and normal_notes: # if time modification
                            time_modification = Fraction(int(actual_notes), int(normal_notes))
                        else:
                            time_modification = Fraction(1, 1)
                        displayed_duration = duration * time_modification

                        # create Note object                
                        n = Note(note_name, duration, displayed_duration, bar_number, bar_offset, is_grace_note, grace_slash)            

                        # tuplet                
                        tuplet = note.find('notations/tuplet')
                        if tuplet is not None:
                            if tuplet.get('type') == 'start':
                                actual_notes, normal_notes = int(actual_notes), int(normal_notes)
                                if actual_notes == 3 and normal_notes == 2:
                                    n.tuplet_begin = '(3'
                                elif actual_notes == 5:
                                    n.tuplet_begin = '(5'
                                else:
                                    raise Exception('unrecognized tuplet: %d/%d' % (actual_notes, normal_notes))
                                #n.tuplet_begin = '(%d' % int(Fraction(actual_notes, normal_notes) * 2)  # TODO: make more generally applicable
                            elif tuplet.get('type') == 'stop':
                                n.tuplet_end = True

                        # accidental
                        if not note_name in 'zx': # unless rest or invisible rest
                            alter = int(note.findtext('pitch/alter', '0'))
                            try:
                                if alter != measure_accidentals[note_name] or note.find('accidental') is not None:
                                    n.accidental = {-2: '__',
                                                    -1: '_',
                                                     0: '=',
                                                     1: '^',
                                                     2: '^^'}[alter]
                                    measure_accidentals[note_name] = alter
                                    notes_with_accidentals_in_this_measure.add(note_name)
                            except KeyError: print "Error processing accidental. Skipping..."

                        # tie            
                        tie = note.find('tie')
                        if tie is not None and tie.get('type') == 'start':
                            n.tie = '-'

                        # slurs
                        for slur in note.findall('notations/slur'):
                            if slur.get('type') == 'start':
                                n.slur_begin = n.slur_begin + '('
                            if slur.get('type') == 'stop':
                                n.slur_end = n.slur_end + ')'                    

                        # ornaments
                        for key, value in note_ornamentation_map.items():
                            if note.find(key) is not None:
                                n.ornaments = n.ornaments + value

                        # fingering                                                
                        fingering = note.find('notations/technical/fingering')
                        if fingering is not None:
                            n.ornaments = '!%s!' % fingering.text + n.ornaments
                            
                        # spacing due to beam ends or long notes
                        if not is_grace_note:
                            beams = [beam for beam in note.findall('beam') if beam.text in ['begin', 'continue', 'end']]
                            all_beams_end_here = beams and not [b for b in beams if b.text != 'end']                
                            if all_beams_end_here or duration >= Fraction(1, 4) or (duration < Fraction(1, 4) and len(beams)==0):
                                n.trailing_space = ' '
                                ##if duration < Fraction(1, 4) and len(beams)==0:
                                ##    n.trailing_space = ' !%s!' % len(beams)

                        # chord
                        if note.find('chord') is not None:
                            n.trailing_space = ''  # beam detection only works for first chord note, so erase any incorrectly generated space
                            last = voices[voice].pop()
                            if not isinstance(last, Chord):
                                last = Chord([last])
                            last.add(n)
                            n = last

                        # lyrics 
                        elif voice == first_voice and not is_grace_note and note_name not in 'zx':                            
                            for lyric_number in lyric_numbers:
                                lyrics_text = '*' # skip this note unless we find a lyric element that matches the current lyrics number
                                for lyric in note.findall('lyric'):                                                                        
                                    if lyric_number == lyric.get('number', '1'):
                                        # match found, so get the lyrics text (replace spaces and elision elements by '~')
                                        lyrics_text = ''
                                        for lyr_element in lyric:
                                            if lyr_element.tag == 'elision':
                                                lyrics_text = lyrics_text + '~'
                                            elif lyr_element.tag == 'text':
                                                lyrics_text = lyrics_text + (lyr_element.text or '').replace('-', r'\-').replace(' ', '~') # escape '-' characters
                                        # add - and _ characters
                                        if lyric.findtext('syllabic') in ['begin', 'middle']:
                                            lyrics_text = lyrics_text + '-'                                    
                                        if lyric.find('extend') is not None:                                        
                                            lyrics_text = lyrics_text.replace('*', '') + '_'
                                # if the current element is silence and the last element was '_', then discard the silence since the '_' covers this
                                if lyrics_text == '*' and lyrics[lyric_number] and lyrics[lyric_number][-1].endswith('_'):
                                    lyrics[lyric_number].append('')  # adding '' ensures that the if condition is not true next time around
                                else:
                                    lyrics[lyric_number].append(lyrics_text)                                                                
                        
                        # add note/chord to its voice            
                        voices[voice].append(n)                        
                                            
                        if not is_grace_note:
                            bar_offset += n.duration

                    # backup
                    elif measure_element.tag == 'backup':
                        duration = Fraction(int(measure_element.findtext('duration')), cur_divisions) / 4
                        duration.reduce()
                        bar_offset -= duration

                    elif measure_element.tag == 'barline':
                        for voice_name, voice in voices.items():                            
                            barline = measure_element
                            location = barline.get('location')
                            bar_style = barline.findtext('bar-style')
                            if bar_style == 'light-light':
                                s = '|-|'
                            elif bar_style == 'light-heavy':
                                s = '|]'
                            else:
                                s = '|'
                            repeat = barline.find('repeat')
                            if repeat is not None:
                                if repeat.get('direction') == 'forward':
                                    s = '|:'
                                else:
                                    s = ':|'                        

                            # handle segno, coda, fermata
                            ornament = None
                            if barline.find('segno'):
                                ornament = 'S'
                            elif barline.find('coda'):
                                ornament = 'O'
                            elif barline.find('fermata'):
                                ornament = 'H'
                            if ornament:
                                for voice in voices.values():
                                    voice.append(ornament)
                            
                            ending = barline.find('ending')
                            if ending is not None:
                                if ending.get('type') == 'start':                                    
                                    if part_no == 0 and voice_name == first_voice: # only read endings for first part since this is the way ABC handles it                                                
                                        text = ending.text or ending.get('number')
                                        if text is None:
                                            text = ''
                                        elif text.strip() in '1 2 3 4 5 6 1. 2. 3. 4. 5. 6.':
                                            text = text.replace('.', '') # delete any trailing dot after the ending number
                                        else:
                                            text = '"%s"' % text
                                        s = s + '[' + text
                                else:
                                    s = s + '|-|'
                                    
                            voice.append(s)                    
                            debug_print(s)

                    elif measure_element.tag == 'direction':
                        direction = measure_element
                        s = None
                        if direction.find('direction-type/coda') is not None:
                            s = 'O'
                        elif direction.find('direction-type/segno') is not None:
                            s = 'S'
                        elif direction.find('direction-type/words') is not None:
                            words = direction.find('direction-type/words')
                            offset = words.get('default-y')
                            text = direction.findtext('direction-type/words', '').strip()
                            ##if text.lower() == 'fine':
                            ##    s = '!fine!'
                            ##elif text.upper() == 'D.C.':
                            ##    s = '!D.C.!'
                            ##elif text.upper() == 'D.S.':
                            ##    s = '!D.S.!'
                            if text == '$':  # Sibelius sometimes seems to use this for segno
                                s = 'S'                            
                            elif offset and int(offset) < 0:
                                s = '"_%s"' % text
                            else:
                                s = '"^%s"' % text 
                            s = s.replace('\n', ' ')                                                            
                        if s:
                            voices[first_voice].append(s)
                            #for voice in voices.values():
                            #    voice.append(s)

                    elif measure_element.tag == 'harmony':
                        voices['1'].append(xml_harmony_to_abc(measure_element))

                    elif measure_element.tag == 'print':
                        print_element = measure_element                
                        if print_element is not None and print_element.get('new-system') == 'yes':
                            for voice in voices.values():
                                voice[-1] = voice[-1] + '\n'
                            for lyrics_number in lyrics:
                                lyrics[lyrics_number].append('\n')

                for voice in voices.values():
                    voice.append('|')            
                debug_print('|')
                        
            for voice in voices:                
                fix_chords(voices[voice])
                fix_tuplets(voices[voice])
                voices[voice] = introduce_grace_starts_and_ends(voices[voice])
                voices[voice] = fix_barlines(voices[voice])                
                fix_slurs_before_repeat_ends(voices[voice])
                introduce_broken_rythms(voices[voice])
                pass
            
            for voice_name, voice in sorted(voices.items()):
                if not voice_name and not voice:
                    continue
                s = ''.join(map(unicode, voice))                
                s = s.replace('|-|', '||').replace(':|||:', '::').replace('||:', '|:').replace(':||', ':|').replace('||[', '|[').replace('||[', '|[').replace('|-|', '||').replace('|||', '||').replace('|||', '||').replace(']|', ']').replace('|]|', '|]').strip()                
                if s.endswith('||'):
                    s = s[0:-2] + '|]'                
                if num_parts > 1:
                    if voice_name:
                        voice_name = part.get('id') + '_' + str(voice_name)
                    else:
                        voice_name = part.get('id')
                # if this is the first voice, then pair up each line of note output with the lyrics lines (if there are any)
                if voice_name == first_voice:
                    result = []
                    notes_lines = s.split('\n')
                    lines_for_each_lyrics = [' '.join(lyrics[lyrics_number]).split('\n')
                                             for (lyrics_number, lyrics_parts) in sorted(lyrics.items())]
                    for line_no in range(len((notes_lines))):
                        result.append(notes_lines[line_no])
                        for lines in lines_for_each_lyrics:
                            if re.search(r'[^-*_ ]', lines[line_no]):  # if line is not empty
                                result.append('w: %s' % lines[line_no])                    
                    s = '\n'.join(result)
                parts.append(('V:%s' % str(voice_name), s))            

        file_numbers = [int(x) for x in re.findall(r'(\d+)', filename)]
        if file_numbers and 0 <= file_numbers[-1] <= 100000:
            tune_fields.insert(0, Field('X', str(file_numbers[-1])))
        else:
            tune_fields.insert(0, Field('X', '1'))
        tune_fields.append(Field('L', str(default_len)))
        ##tune_fields.append(Field('R', ''))
        ##tune_fields.append(Field('O', ''))
        output = StringIO.StringIO(u'')
        for f in tune_fields:
            if f.field_name != 'K':
                output.write(unicode(f).replace('[', '').replace(']', '') + '\n')        
        for f in tune_fields:
            if f.field_name == 'K':
                output.write(unicode(f).replace('[', '').replace(']', '') + '\n')
        if not [f for f in tune_fields if f.field_name == 'K']:
            output.write('K:C\n')
        for pname, p in parts:
            if len(parts) > 1 and pname:
                output.write(pname + '\n')
            lines = p.split('\n')
            for line in lines:
                output.write(line.strip() + '\n')
        results_for_different_L_fields.append(output.getvalue())

    # use the L-field that gives the shortest output (but add some extra penalty for using many '/' characters) 
    len_and_texts = [(len(s) + s.count('/')*0.15, s) for s in results_for_different_L_fields]  
    len_and_texts.sort()
    return len_and_texts[0][1]
Beispiel #36
0
    #   also numerator must be < denominator
    #   also if numerator is divisible by 10, denominator can't be

    # keys are numerators, values are list of possible denominators
    denoms_by_num = generate_denoms_for_nums(nums)

    # where we'll store the Fractions that cancel to same value
    fractions_to_keep = []


    # get the cases where they are the same as their form when a common
    # digit removed

    for num, denom_list in denoms_by_num.items():
        for denom in denom_list:
            fraction = Fraction(num, denom)

            # generate all possible fractions by removing those common digits
            cancelled_fractions = fraction.generate_cancelled_fractions()

            # determine if any of those possible fractions equals the original

            fraction_reduced = fraction.get_reduced()

            for cf in cancelled_fractions:
                cf_reduced = cf.get_reduced()

                if fraction_reduced == cf_reduced:
                    fractions_to_keep.append(fraction)

    assert len(fractions_to_keep) == NUM_FRACTIONS_TO_FIND
Beispiel #37
0
 def test_get_reduced_2_4(self):
     original_fraction = Fraction(2, 4)
     reduced_fraction = original_fraction.get_reduced()
     correct_reduced_fraction = Fraction(1, 2)
     self.assertEqual(correct_reduced_fraction, reduced_fraction)
     return
Beispiel #38
0
 def test_get_reduced_2_3(self):
     original_fraction = Fraction(2, 3)
     reduced_fraction = original_fraction.get_reduced()
     self.assertTrue(original_fraction == reduced_fraction)
     return
Beispiel #39
0
 def test_get_reduced_1_1(self):
     original_fraction = Fraction(1, 1)
     reduced_fraction = original_fraction.get_reduced()
     self.assertTrue(original_fraction == reduced_fraction)
     return
Beispiel #40
0
 def test_generate_cancelled_fractions_1(self):
     f = Fraction(13, 39)
     answer = [Fraction(1, 9)]
     self.assertEqual(answer, f.generate_cancelled_fractions())
     return
Beispiel #41
0
 def test_get_gcd_1_2(self):
     f = Fraction(1, 2)
     self.assertEqual(1, f.get_gcd())
     return
Beispiel #42
0
 def test_get_gcd_2_3(self):
     f = Fraction(2, 3)
     self.assertEqual(1, f.get_gcd())
     return
Beispiel #43
0
 def test_get_gcd_2_4(self):
     f = Fraction(2, 4)
     self.assertEqual(2, f.get_gcd())
     return
Beispiel #44
0
 def test_get_common_digits_2(self):
     f = Fraction(12, 21)
     answer = set('12')
     self.assertEqual(answer, f.get_common_digits())
     return
Beispiel #45
0
 def test_get_gcd_8_12(self):
     f = Fraction(8, 12)
     self.assertEqual(4, f.get_gcd())
     return
 def test_cant_simplify(self):
     a = Fraction(7, 23)
     a.simplify()
     self.assertEqual(a.nominator, 7)
     self.assertEqual(a.denominator, 23)
Beispiel #47
0
 def test_generate_cancelled_fractions_2(self):
     f = Fraction(23, 32)
     answer = [Fraction(2, 2), Fraction(3, 3)]
     self.assertEqual(answer, f.generate_cancelled_fractions())
     return