CONSONANT CHORD MODEL OF MUSICAL COMPOSITIONS FOR HARMONIZING MELODIES BY A GENETIC ALGORITHM

О.В. Комаров, О.М. Галчонков, О.І. Неврев, О.Ю. Бабілунга. Консонантна акордна модель музичних композицій для гармонізації мелодій генетичним алгоритмом. Незважаючи на досить добре розвинену теорію побудови музичних творів спостерігається недостатнє впровадження комп'ютерних засобів, що полегшують роботу композиторів. Метою цієї роботи є розробка моделі музичних композицій, що дозволяє використовувати генетичні алгоритми для автоматизації додавання акордів до відомої мелодії при максимальному задоволенні правилам музичної теорії. Розроблена нова модель для представлення музичних композицій, дозволяє збільшити швидкість гармонізації заданих мелодій генетичним алгоритмом. Результат отриманий завдяки побудові моделі на більш високому рівні структурної узагальненості, в порівнянні з відомою тональної моделлю. Проведений аналіз тональної моделі показав надмірність області визначення функції якості музичного твору при використанні цієї моделі. Це і призводить до недостатньо високої швидкості гармонізації мелодій. Звуження області визначення функції якості за рахунок більш повного врахування правил гармонії музичних творів дозволило відсікти явно неприйнятні акорди, що і призвело до прискорення гармонізації при використанні розробленої консонантної акордної моделі. Отримані співвідношення дозволяють виробляти перехід від акордної моделі до тональної і від неї до звичайного нотного запису. Чисельне моделювання задачі гармонізації відомої мелодії показало досягнення більш високого рівня гармонізації автоматичними методами в порівнянні з працею композитора, а також істотне прискорення процесу гармонізації при використанні консонантної акордної моделі, в порівнянні з тональної моделлю. Це дозволяє рекомендувати використання розробленої моделі в програмах автоматичної гармонізації мелодій. Внесок проведеного дослідження в теорію генетичних алгоритмів полягає в використаному новому підході до формування хромосом і багатофакторної функції якості, що дозволили ефективно застосувати генетичні алгоритми до задачі гармонізації музичних творів. Практична цінність отриманих результатів полягає в автоматизації праці композиторів, які можуть зосередитися повністю на створенні мелодії. А працю по доповненню мелодії акордами можна перекласти на комп'ютер. Крім цього, отримана висока швидкість гармонізації дозволяє поліпшити якість мелодій, що генеруються, і їх відповідність динаміці подій в комп'ютерних іграх. Ключові слова: генетичний алгоритм, фітнес-функція, хромосома, музична композиція, акорд, правила гармонії

Ключові слова: генетичний алгоритм, фітнес-функція, хромосома, музична композиція, акорд, правила гармонії O. Komarov , O. Galchonkov, A. Nevrev, O. Babilunga.Consonant chord model of musical compositions for harmonizing melodies by a genetic algorithm.In spite of the well-developed theory for the musical compositions creation, there is a lack of implementation of computer program methods that facilitate the work of composers.The purpose of this work is to develop a model of musical compositions that allows using genetic algorithms for automatization the addition of chords to a well-known melody with maximum satisfaction the rules of musical theory.A new model has been developed for representing musical compositions, which makes it possible to increase the speed of harmonization of specified melodies by a genetic algorithm.The result is obtained due to the construction of the model at the higher level of structural generality, compared with the well-known tonal model.The analysis of the tonal model shows the redundancy of the definition area of the quality function for a musical composition using this model.This leads to insufficiently high speed of melody harmonization.Limitation the definition area of the quality function by taking into account the rules of harmony for musical composition allowed to exclude clearly inappropriate chords, which led to acceleration of harmonization with the use of the developed consonant chord model.The obtained relations allow the transition from the chord model to the tonal model and from it to the usual musical notation.Computer modeling of harmonization for the known melody showed higher level of harmonization by automatic methods in comparison with the work of the composer, as well as significant acceleration of the harmonization process using the consonant chord model, Introduction.The use of computer technology in all spheres of human activity significantly increases the capabilities of a person.Writing music as a type of creative activity is no exception.If, during Mozart's time, along with the usual approach, dice were used to write the new melody, which determine the sequence of the finished note fragments, the release in 1992 of the fundamental work of Yannis Xenakis [1] was a powerful impetus for the wide use of set theory, probability theory and other branches of mathematics to create music.
Since music is intended for human perception and now the classical theory of music is well developed, there is a set of rules that music must satisfy for a harmonious sound [2,3,4].The mathematical community made great efforts to formalize these rules and translate them into the language of mathematics in order to use the possibilities of computer technology.
The most advanced results were obtained using algebraic, geometric, and combinatorial approaches, as well as graph theory [5].However, these approaches still impose significant restrictions on the ability to create music compared with the composer's emotional inspiration and require further development.Therefore, the most relevant currently are the methods that do not impose additional restrictions and allow the use of the classical theory of musical harmony [6].
These methods can be divided into two significantly different basic approaches.The first approach involves the analysis and use of harmony chords as well as the statistical properties of their combinations in the musical works already created by various composers to create new musical compositions.This includes, for example, work on identifying patterns and their permissible combinations [7,8], using the theory of automata [9], Petri nets [10], neural networks [11,12], and also combining and mixing different harmonic subspaces to use when creating new music works [13].
The second approach to harmonize musical compositions uses the direct use of the rules of the musical harmony theory [14].For this purpose, a quality function should be defined, usually representing a weighted sum of the coefficients of musical harmony theory individual rules fulfillment.Harmonization of musical composition will be achieved in providing a global extremum of this function.Due to the large number of rules in musical theory and their empirical nature, the quality function is multiextremal with a complex surface shape.The task of taking into account all the rules of harmony without the use of computing technology falls entirely on the composer, which significantly limits his capabilities.The algorithms and software created within the proposed approach should release the composer from routine work and thus free up his resources and expand possibilities for musical creativity.
Among the many algorithms that are used to find the global extremum of multidimensional multiextremal functions, one of the most promising for harmonizing musical compositions is the genetic approach [15 -17].The main problem when using the genetic approach is a large amount of computation.Therefore, the development of algorithms that make it possible to reduce the required amount of calculations to find the global extremum of a very complex quality function is actual.
Related works and problem formulation.Considering the extremely wide possibilities of combinations in the creation of musical works, the use of genetic algorithms in music presupposes a primary three components [18].
The first one is the search area, which can be limited by style, tempo, rhythm, melody, etc. [19].These natural limitations are determined by the direction of the creative intentions of the composer, the purpose of the music, and the role that the projected algorithm will perform.
The next area is the original representation of music or the musical alphabet, with the help of which the pitch, rhythm, tempo, combinations of sounds and other parameters of musical building blocks are set.Here it is possible to choose from a classical recording of a musical work with the help of notes [14] or the development of a special language [20] to visual presentation in the environment of the computer music studio [21,22].The degree of convergence of the genetic algorithm to the desired solution will depend on how well this initial representation will be chosen.
The third area is the choice of the quality function used, or in the terminology of the genetic approach, the fitness function.In a number of articles, expert estimations [23] or sets of well-known musical works [24 -26] were used to evaluate the quality function at each step of the genetic algorithm.These approaches have been developed in the concept of an automatic fitness function with multiobject optimization [27].
Significant acceleration for the searching of the quality function extremum can be achieved by replacing strict rules of musical harmony onto the using of statistical distribution of notes in chords and the sequence of chords for certain music styles [28].However, from the point of view of minimizing the influence of restrictions on the expressiveness of the resulting music compositions and maximizing the possibilities in using computer technology, these approaches to the choice of quality function are not effective.
More promising approach is the direct use of the laws of musical harmony for formation of a fitness function, as it was done, for example, in [29,30].In [29] harmonization of the musical composition is performed for a given melody and in [30] the sequence of chords is harmonized.Thus, the most rational approach to ensure the freedom of the composer creativity seems is to limit the region of the searching an extremum of the quality function by a genetic algorithm by already human created melody and rhythm.In other words, the composer comes up with a melody and rhythm in the form of a sequence of single notes, and the software complements these notes with chords that meet all the requirements of classical musical theory.
In this version, very important is the model of music representation, which makes it possible to effectively automate the harmonization of a melody by a genetic algorithm.In [14], a fairly generic universal model is presented that imposes almost no restrictions.Its disadvantages include the admissibility to get some chords and their sequences, which obviously do not satisfy the laws of musical harmony.This leads to a complication of the quality function surface and to a corresponding slowdown in the convergence of the genetic algorithm to the global extremum.
In general, models of musical compositions used for harmonizing melodies by genetic algorithms must satisfy a variety of requirements.On the one hand, models of musical compositions should be formal, declarative and explicit [31], and they should also have the greatest possible expressive completness and structural generality [32].On the other hand, the use of musical compositions models in genetic methods imposes additional requirements in terms of their effective using as chromosomes [33,34].In addition, evaluation of the effectiveness of the model for the formation of chromosomes also implies the evaluation of the following properties [35,36]: nonredunancy, legality, completness, lamarckian property, causality.
Therefore, the development of new models that take into account the special features of the subject area is actual.This will make it possible to exclude obviously unacceptable solutions from the search area, which should accelerate the convergence of the genetic algorithm to the global extremum of the quality function.
Purpose of the work.The aim of this work is to develop a model of presenting music compositions used for the harmonization of these compositions in genetic algorithm and allows to speed up the process of harmonization of the composition.
To achieve the goal, the following tasks were set: -analyze the characteristics of the well-known tonal model of musical compositions in terms of the level of its structural generalization and redundancy of the search for solutions in the task of harmonizing melodies; -consider the features of the rules of musical compositions harmony, allowing to apply restrictions on the area of search for solutions in the task of harmonizing melodies and develop a model with a higher level of generalization; -formulate expressions for the conversion of a consonant chord model into a tonal one for subsequent translation into a musical notation; -to carry out a simulation of the solution of the task of harmonization of a given melody by a genetic algorithm for comparing the effectiveness of using a consonant chord model and a tonal model.
The basic concepts used for building models of musical compositions and their use in methods of harmonization.
We will call a music composition any combination of musical sounds that are organized together in time and pitch in a certain way.Musical sounds are specially selected sound waves that are opposed to noise waves and historically form a musical system [37].
Musical sound is characterized by a certain pitch, duration and time position (Fig. 1).The disposition of the sound determines when the oscillation starts and the duration determines how long it lasts.In classical music notation the duration of sounds and their disposition is determined not in absolute, but in relative, as a rule, multiples of 2, values.The pitch characterizes the oscillation frequency.In the classical European musical system there is a finite, discrete, ordered set of musical sound pitches, in which the frequency ratio between neighboring elements is equal to 12 2 in hertz.This difference in pitch between serial sounds of the music system is called a semitone.The frequency-ordered set of all pitches is called a sound order.
A model of a musical composition will be called any mathematical object, with the help of which it is possible to reproduce a set of musical sounds represented by at least the three parameters mentioned: pitch, duration, and disposition.
The simplest models of musical compositions encode these three parameters explicitly.We will call such models high-pitch.A typical example of such model is a classical music notation.Another vivid example of a high-pitch model is MIDI format [38] -where sounds are represented as events having a pitch and duration, which playback is assigned to a specific disposition.
We will say that two sounds intersect if they sound simultaneously, that is, if the disposition of one of them lies in the interval between the disposition and the sum of the disposition and duration of the other.The set of sounds, each pair of which intersects, will be called an intersection, or consonance (Fig. 2).An intersection consisting of two sounds will be called an interval.The length of the interval is the pitch difference between the highest and lowest pitch of interval sounds.The main object of study of musical harmony is the sounds intersection and their sequence.Features of human perception of sounds intersection cause need for regulation of their structure.So, some consonances are considered pleasant, consonant, and some -unpleasant, dissonant.The goal of harmony is to achieve a harmonious, consonant sound of all intersections of the composition [2,3].
Composition in harmony is considered as a combination of two components: melody and accompaniment.A melody is a sequence of sounds expressing the main musical content of a composition.The sounds of the melody do not intersect with each other.Accompaniment is a set of all sounds intersecting with sounds of a melody.The purpose of the accompaniment is to accompany and emphasise the melody.
According to this consideration, the generation of a musical composition is divided in two stages: 1. Formation of melody.

Accompaniment selection.
Melody harmonization is the process of selecting the accompaniment that forms consonant harmonies with the melody.Harmony defines a number of requirements that apply to the composition in the form of rules that determine which combinations of sounds can be used and which are not [14,36,39,40].The main attention is paid to the structure of the intersections used in the composition, as well as their sequences.A composition that follows the rules of harmony is considered to be harmonious.
The main way to build intersections of musical sounds is tonality.The tonality sets a special metric on the sound space range used to measure the lengths of the intervals.Harmony rules usually use a metric that is defined by tonality and represents such interval lengths as the third, fifth, seventh, etc.
The set of musical sounds pitch or scale is divided into subsets called octaves and pitch classes (Fig. 3).Pitch classes include pitch values, the ratio of any pair of which is a multiple of 2. These pitches are considered to be similar for human perception.Some pitch classes have their own names -for example, G (or "sol").There are 12 altitude classes in total, and they are denoted by capital Latin letters: Octaves combine the pitches of the scale that are limited to values whose ratio is 2 (with the upper limit excluded from the octave).The set of octaves is ordered, so they are called simply by number.Any octave intersects with any pitch class, and the intersection always contains only one element.Thus, any pitch can be characterized using the pitch class and the octave to which it belongs.For example, the pitch of 440 is called A4 (or "la" of the "first octave").
Tonality is a principle that determines the sounds of which pitch classes will be used in the composition, as well as the role of the sounds within the composition.The pitch class, which is included in the tonality, has a certain function in it and is called the tonality degree (Fig. 4).As a standard way, from the 12 pitch classes of the scale, the tonality uses only 7. As degrees, the pitch classes are ordered among themselves by number (Table 1).
Table 1 The degrees of the seven major keys  In the most common keys, natural major and natural minor, the key interval for building harmony is the third.The third is the length of the interval containing the sounds with the difference of the degrees equal to 2.
The intersection of all sounds that sound in a composition at any given time is called a chord.To achieve harmony, we strive to ensure that any chord of the composition can be represented as a set of third.The chords of the tertian structure differ in the number of tonality degrees of sounds included in it (Fig. 5).Despite the fact that every chord in four-part singing consists of four sounds, in the general case, the pitch of each sound can correspond to only one degree.For example, A3, A4, A5, A6 are different pitches of one pitches class A, which in any tonality forms only one degree.
Tertian chord should consist of the sounds of at least three different degrees.A chord made up of three degrees sounds is called a triad.At the same time, in order to form four sounds, one of the degrees is doubled, that is, it is used to form two different chord sounds.Harmonization of melody with triads is one of the most common practices in harmony.Triads allow to harmonize most melodies in a standard curriculum on harmony [2,41].When developing a model, we will limit ourselves only to chords of this type.
A voice is any sequence of sounds without intersections between them.Thus, in the task of harmonizing a melody is always a voice.The accompaniment consists of three other voices.A chord in a consonant composition is an intersection that includes sounds from all voices.
Different styles and genres may have their own characteristics of harmony assessment requirements, so that their sets of harmony rules may vary.However, there are a number of criteria that must be met for any harmonious composition: -composition consists of four voices; -voices are ordered by pitch and have no collisions -a musical sound from a low voice cannot have a pitch higher than the sound from a higher voice with which it intersects; -the distance between every two voices, that is, the length of the intervals formed by them, should not exceed 12 semitones; -the distance between the highest and lowest voices should not exceed 36 semitones; -all chords must have a tertiary structure.
Compositions that meet these requirements will be called consonant.Not every consonant composition is harmonious, but the class of harmonious compositions is contained within the class of consonant compositions.Thus, to describe harmonic compositions, a model capable of describing representatives of the class of consonant compositions is sufficient.It is important that this model should be closed relative to the class of consonant compositions.Outside this class, no solutions can be found.

Tonal model of musical composition.
Model that represent the pitch using a combination of two values -the degree of tonality and octave we will call tone model.Such models are widely used in genetic methods of harmonization [14,36,39].As a tonal model, we consider in detail the tonal model of a musical composition presented in [14].
The model is a twodimensional matrix, the elements of which encode the pitch of the sounds, and the vector of chord sounds duration attached to this matrix (Fig. 6).

Tonal model of musical composition
The rows of the matrix specify the individual voices.Matrix columns correspond to chords.The elements of the duration vector indicate the duration during which all sounds of the corresponding chord are played.The time in the model is presented from left to right.That is, the first left chord starts to sound, then the next right chord, etc.Thus, the position of the sounds is calculated as the sum of the durations of all previous chords.
Each pitch P in the model is represented by a vector consisting of three elements: the tonality degree D, the octave OC and the altration sign ALT, a special designation that allows you to increase or decrease the pitch by a semitone.Alteration signs were taken from classical musical notation and are used to enhance the expressiveness of the model.
The model is supplemented with a special function d, which selects and numbers the pitch classes as grades of tonality.Accordingly, there is also an inverse function d -1 , which associates a certain pitch class with the grade number.
The pitches of the sounds of the model are calculated according to the formula: The tonal model is redundant.The use of alteration signs means that the same sound can have at least two different ways of recording, and this recording may also depend on the tone used.For example, in the key of C dur, the records P 1 =(7, +1, 1) and P 2 =(1, 0, 2) denote the same pitch C 2 .Considering that each sound of a composition can have multiple recordings, there are a significant number of ways to record the same composition.The redundancy of the model significantly slows down the convergence of the algorithm to the optimum.
The tonal model is unacceptable for the class of consonant compositions.The tonal model provides the presence of only one property of the consonant composition -the presence of four voices.The model itself, without the use of additional efforts, for example, specialized genetic operators, does not even allow to maintain the requirement of voices right ordering or limiting pitch distances between voices [14].Also in this model you can record chords not only in the tertian order.
One of the reasons for the redundancy of the tonal model, which leads to the inadmissibility of this model for consonant compositions, is its weak structural generality.Increasing the structural generality will allow to narrow the class of the described compositions.
At different structural levels of the model there are different rules of harmony.Explicit selection of parameters in the model that are important for harmonization is an essential criterion for the choice of the model in optimization methods [33,34].Let us consider three levels of structural generality of models of musical compositions, depending on the amount of concepts and knowledge that one must have in order to select certain parameters (Table .2).It is inefficient to combine all the above properties defined for different structural levels of a chord in one model, as it leads to excessive information content and requires constant coordination of different levels with each other.Therefore, when developing a model, it is necessary to use a compromise solution, distributing the priorities of different levels of structural description.
The basis of musical harmony is a system of functional relations between sounds, and the main structural element of a harmonious composition is a chord [2,3].Therefore, it can be said that parameters at higher structural levels have higher priority for the determining of harmony.
The tonal model provides a description of the composition on the tonality structural level.By abstracting information about a specific tonality, it can significantly reduce the calculation of the intervals tonal length, which also allows us to easily change the tonality of the composition.The harmony of the relations between sounds of different degrees expressed in such model is preserved when the tonality changes.However, more significant parameters of higher structural levels are available in this model only through additional computation, which significantly limits it.
Chord consonant model.
The disadvantages of the tonal model encourage the development of a more effective model.The developed model should: -be valid for consonant compositions in genetic methods; -be closed on the class of consonant compositions for genetic operators of general purpose; -be explicit at a higher functional level of structural generality.It is possible to achieve an increase in structural generality by constructing a model based on a greater amount of knowledge about the music subject domain [33,34].Understanding the consonant musical composition as a sequence of chords, allows us to explore the patterns of chord formation in the tertian structure.This analysis will help to identify the most important features of such chords in order to exclude the possibility of the chords formation with non tertian structure and exclude redundant descriptions of the same chords.Therefore, it will be effective to describe the composition at the highest structural level and further to synthesize musical sounds in the order of "top down".
Chord sounds are always ordered by their pitch.Since this order determines which sound belongs to which voice, we will call this order as voice order.However, to introduce functional structural level parameters at a set of chord pitches, it will be necessary to define a different order.This order is based on the tertian structure of the chord, so we will call it tertian.
If we arrange the chord sound degrees by the third, we can point the increase of the tonality degrees by the third.This increase sets tertian order (Fig. 7).Its first element is the "edge" from which the increase begins.This degree is called root.The subsequent degrees are called respectively the third and fifth, in accordance with the lengths of the tone intervals that they would form with root, if this order coincided with the voice order.
In this case, the number is set for the degree, so several sounds in the chord can be called a root or a fifth.Also note that the tertian and voice order do not coincide, and that the sounds in a traditional musical notation are visually ordered according to the voice order, which, however, does not negate the tertian order inherent in the chord (Fig. 8).Since the entire set of harmony parameters is redundant, let us consider, starting from the highest level of generality, which of them are sufficient for the complete formation of a chord and the subsequent calculation of the remaining parameters.
Under the function of the chord we understand its harmonic value within a single tonality [42].The function of the tertian chord is determined by the degree of root.
The inversion and position of the chord describe the relationship between the tertian and voice orders.The inversion indicates the number in the tertian order of the sound of the lowest voice.Position indicates the location of middle voices.In close position the sounds of middle voices have the same position in the tertian order as in the voice order, and in the broad position -the opposite.
For triads, it is also important to specify which of the steps is doubled.Since, as a rule, doubling of the third is prohibited, the doubling parameter indicates either to root or to third.
These four parameters, together with the pitch of the melody for which the chord is built, are enough to completely form a triad.Therefore, it is proposed to describe the chords of the composition with the following parameters: -function f, -inversion i, -position p, -repeat Let us set a list of valid values for these parameters.The basis for a chord building is the sound of a melody, which we harmonize with this chord.This sound belongs to a certain degree of tonality and has a definite position in the triad structure.The sound of a melody can be in one of three possible positions: root, third or fifth, and accordingly can belong to triads of only three functions.We denote these functions by the values 1, 2, and 3, respectively, in accordance with the number of the melody sound degree in the tertian chord order.
Inversion points to the voice position of one of the chord degree, namely, the degree of the lowest voice.Similar to the function notation, an inversion can be marked as 1, 2, or 3, where degree is encoded by its number in the tertian chord order.
The repeat points either to root or fifth, so it has only two valid values 1 and 3.The repeat value is ignored if the function and the inversion are equal.
Position can be open or close.The close position corresponds to the coincidence of the voice and tertian orders, and vice versa.We can denote a close position with a value 1, and an open position with value 2.
Thus, all parameters can be denoted by a small set of integer values.Understanding the composition as a sequence of N chords, we can represent its model as a matrix of 4×N integers, an additional melody vector 1×N and a vector of durations 1×N (Fig. 9).
A melody is attached to the matrix as a sequence of musical sounds represented by vectors containing the values of the pitch and the duration of the sound.The pitch of the melody sounds allows us to build chords by parameters from the matrix, and the duration allows us to determine the duration and position of the formed chords by complete analogy with the tonal model.
Applying a higher level of structural generality, we obtain the completeness of genetic operators in the class of consonant compositions defined by this model.This is achieved due to the fact that all compositions that can be recorded as a consonant chord model are also consonant, as well as the fact that any combination of the values of model parameters (within their range of definition) is a certain consonant composition.Thus, whatever genetic operator of crossing or mutation would be applied to the composition in the model, as a result, consonant compositions will be formed.
Let us consider the relevance of using the developed model in genetic methods.
The consonant chord model is characterized by conditionality -the effects of changes in model parameters are localized in chords, which are described by these parameters.The model also has the Lamarckian property, since the interpretation of each chord is completely independent of the neighboring chords.
The model has admissibility.Any composition described by this model is consonant, which means it can be a solution of the harmonization problem.The model is incomplete.The model allows describing only those consonant compositions that are formed using triads.This model feature makes it difficult to use it in problems of composition analysis, however, it still makes it possible to effectively use model in problems of melody generation, such as harmonization.
The model has redundancy.The using of the repeat parameter is useless when the chord has the same value of function and inversion.However, it should be noted that the redundancy of the consonant chord model is significantly lower than the redundancy of the tonal model.Each sound of the tonal model could be represented by at least three different vectors.So any chord could be represented in 3 4 different ways.In the chord model, redundancy occurs not for any chords, and if it does, it results in only to two different forms of recording.
Transformation of consonant chord model to tonal model.Let us show a transformation that will allow proceeding from a chord description of the composition in the chord model to a greed description in the tonal model.
The general process of sound formation from the tonal model involves the following steps.First of all, we determine degree of the harmonized melody note.As we know position of the third of this degree in the chord one can determine its function and use it to determine the set of all chord degrees.Next we find which degree will belong to the lower sound, and which degree will be doubled.After that it is necessary to arrange the degrees of the middle voices relative to each other.Further, from the degrees it is possible to form the pitch of the sounds, placing the neighboring sounds at intervals of no more than an octave.
In the tone model, the chord is the vector A=(P 1 , P 2 , P 3 , P 4 ), where P n is the pitches represented by vectors of the form P n =(d n , a n , o n ), and Р 1 is the melody pitch.In the consonant chord model, the chord is represented by the vector A=(m, f, i, p, r).Let us show how it is converted to into A=(P 1 , P 2 , P 3 , P 4 ).
Let d be the function that determines the tonality: for each pitch it defines the degree of tonality and also let О be the function that assigns to each pitch the octave in which it is located.Accordingly, the functions d -1 and О -1 are inverse functions to them.
Considering that we know the pitch value of the melody m, we can easily form The value of the alteration sign a 1 =0, as well as for any other pitch formed with the help of the chord model.
Using the parameter f, we form the set of chord degrees according to the formula (1).In total, there are two such steps to form, given that one of them already exists and is equal to Here and further, the degree order is denoted by the superscript, and the voice order is denoted by the subscript.That is, record d 1 means "degree of the first (upper) voice)", and record d 1 means "root degree".
The inversion parameter i allows us to determine the degree of sound in the lower voice, so d 4 =d i .
After determining the degrees d 1 and d 4 , it is necessary to arrange in order the remaining degrees and assign values to the degree d 2 and d 3 .We call these degrees free and denote their place in tertian order by an asterisk d * and a double asterisk d ** , where d * ≥d ** .The procedure for assigning free degrees to voices has the following logic.If the position parameter is p=0, then d 2 =d * and d 3 =d ** .If p=1, then d 3 =d * and d 2 =d ** .
If d f =d i , two free degrees remain unordered.If d f ≠d i , then after the determination d 1 and d 4 , there is only one free degree.Since we need to have two degrees, we form an additional degree d', which will be equal to d 1 or d 3 .Using repeat parameter r, we set d'=d r .
Having obtained all the d n degree values, we define the octaves of sounds recursively using the formula (3): , .
After that, we can define specific chord pitch according to the rule of formation of tonal model pitch, using the functions d and O in the formula (1).
Experimental results.
Let's compare the computation time of the genetic method of harmonization using two different models: tonal and consonant chord.
The standard way to evaluate harmony is a list of harmony rules that describes the relationships of adjacent chords [14,19,40].The set of rules has the general form F={f | f : A×A→{1, 0}} in which rule f gives the value 1 in case a pair of chords А violates it, and 0 otherwise.
Harmony H is a value that can be calculated using the following formula for composition c using the F rules: where c is the composition; N is the number of all chords; Q is the sum of the weights of all rules; f i is the i-th harmonic rule; F -number of rules; q is the function of the weights of the rules; a j -j-th chord in composition.
For the simulation experiment, the following list of rules was used (Table 3).Since both the tonal and the chord model describes only four-part harmony compositions the condition of the four-part harmony composition cannot be violated and therefore was excluded from the rules.Horizontal interval is a sequence of two series sounds of one voice.Its length is the difference of these sounds pitches.Chord progression is a sequence of chords whose functions are matched with each other.Chord progression is formed using the rules that show for each chord the functions of the chords, which can be used after the given one.These rules are listed in Table 4.The table shows whether it is possible to use the chord of F2 function after the chord of F1 function.

Features of the models used.
The genetic algorithm for optimizing the quality function was implemented in a typical way [15].Candidates for breeding are selected by binary tournament method.Crossing is a single point crossover.Chord sequence are crossbreed.Each pair of selected genotypes is crossed.A lot of parents with their descendants, go into the next generation.Mutations are point-like: each numeric element of the chromosome matrices can get a random value within its range of possible values.Melody values cannot mutate.
The tonal model is a matrix of 4×3×N integers.The consonant chord model is a two-dimensional matrix of 4×N integers.The initial populations are sets of m such matrices and each element is filled with random values.

Results of experiment.
For the simulation experiment, the melody of the first seven bars in composition "The Savior is Waiting", written by Ralph Carmichael (Fig. 10), was chosen (Free Choir Sheet Music).This composition is written in the classical harmonic style, in four voices, in the tonal model F dur. Melody was harmonized by the genetic method twice using the tone model and consonant chord model.The results are presented in Fig. 11 -13.We can see that for the both model the final value of harmony gets a constant, approximately the same value.However, the use of a consonant chord model allows to achieve stable level much earlier.
In this example, we can see that the time difference is almost doubled.

Fig. 4 .
Fig. 4. A third chord with the designation of pitch classes (characters) and numbers of degrees (Roman numerals) in tonality in C dur

Fig. 3 .
Fig. 3. Division of the scale into octaves and pitch classes

Fig. 5 .
Fig. 5. Several different intersections of the same degree composition

Fig. 10 .
Fig. 10.First seven bars in composition "The Savior is Waiting"

Table 2
Different levels of structural generality of models

Table 3
Harmony rules