public MelodySequence Generate(MelodySequence seq, int seed)
        {
            var targetSeq = NormalizeSequence(seq);

            MelodySequence outputSequence = new MelodySequence();

            var targetSequences = targetSeq.Split(SYNC_AFTER_NOTES);
            int mainDuration = 0;
            int accompDuration = 0;
            foreach(var mel in targetSequences)
            {
                var outputMel = table.Chain(mel.ToArray(), seed);
                MelodySequence outputSeq = new MelodySequence(outputMel);

                while(outputSeq.Duration > mel.Duration)
                {
                    outputSeq.RemoveLastNote();
                }
            //    outputSeq.RemoveLastNote();
                outputSeq.AddPause(mel.Duration - outputSeq.Duration);
             //   outputSeq.RemoveLastNote();

                if (mainDuration > accompDuration)
                    outputSeq.AddPause(mainDuration - accompDuration);

                outputSequence.AddMelodySequence(outputSeq);

                mainDuration += mel.Duration;
                accompDuration += outputSeq.Duration;

            }

            return outputSequence;
        }
 public MetricSimilarity(MelodySequence seq, IMetric metric, SimilarityType type = SimilarityType.Cosine)
 {
     this.metrics = new IMetric[]{metric};
     this.target = seq.ToArray();
     this.type = type;
     this.target_metrics = new Dictionary<Pair, float>[] { this.metrics[0].Generate(this.target) };
 }
Exemple #3
0
 public void Play(MelodySequence seq, PatchNames instrument = PatchNames.Acoustic_Grand)
 {
     if (playingThread != null)
         playingThread.Abort();
     player.SetPatch((int)instrument, 1);
     playingThread = new System.Threading.Thread(() => player.Play(seq));
     playingThread.Start();
 }
 public MetricSimilarity(MelodySequence seq, IMetric[] metrics, SimilarityType type = SimilarityType.Cosine)
 {
     this.metrics = metrics;
     this.target = seq.ToArray();
     target_metrics = new Dictionary<Pair, float>[metrics.Length];
     this.type = type;
     for (int i = 0; i < metrics.Length; i++)
         target_metrics[i] = this.metrics[i].Generate(this.target);
 }
 public CrossCorrelation(MelodySequence seq)
 {
     this.target = seq.ToArray();
     pitches = new double[this.target.Length];
     durations = new double[this.target.Length];
     for(int i = 0; i < this.target.Length; i++)
     {
         pitches[i] = this.target[i].Pitch;
         durations[i] = this.target[i].Duration;
     }
     highest_peak = GetSimilarity(pitches, pitches, durations, durations);
 }
        public StochasticGenerator(MelodySequence[] seqs)
        {
            if(seqs != null && seqs.Length > 0)
                this.base_seq = seqs[0];

            int count = seqs.Length;

            List<int[]> notes = new List<int[]>();

            List<int[]> bayesInputs = new List<int[]>();
            List<int> bayesOutputs = new List<int>();
            notes_map = new Dictionary<int, int>();

            int max_notes = 0;

            int note = 0;
            foreach (MelodySequence m in seqs)
            {
                Note[] song = m.ToArray();

                int[] _notes = new int[song.Length];
                int[] _durations = new int[20];

                for (int i = 0; i < song.Length; i++)
                {
                    var unote = song[i].Pitch + song[i].Duration*128;
                    if (notes_map.ContainsKey(unote))
                        _notes[i] = notes_map[unote];
                    else
                    {
                        notes_map[unote] = note++;
                        _notes[i] = notes_map[unote];
                    }

                }
                notes.Add(_notes);

            }
            max_notes = note;
            Console.WriteLine("Training Pitches");
            pitch_hmm = new HiddenMarkovModel(50, max_notes);
            var teacher = new BaumWelchLearning(pitch_hmm) { Tolerance = 0.0001, Iterations = 0 };
            var __pitches = notes.ToArray();
            teacher.Run(__pitches);
            teacher.Run(__pitches);
            Console.WriteLine("Done training");

            this.MaxGenerations = 2000;
        }
        /// <summary>
        /// Adds a track and returns the reference
        /// </summary>
        /// <param name="seq"></param>
        /// <param name="gen"></param>
        /// <returns>Reference of added track</returns>
        public Track Add(MelodySequence seq, INoteGenerator gen)
        {
            if (gen as DrumGenerator != null || gen.Instrument == PatchNames.Helicopter)
                return AddPercussionTrack(seq, gen);

            Track t = new Track(gen.Instrument, (byte)channelIndex++);
            t.AddSequence(seq);
            ActiveComposition.Tracks.Add(t);
            generators.Add(gen);

            if (OnCompositionChange != null)
                OnCompositionChange(this, new EventArgs());

            return t;
        }
        public GeneticGenerator(IFitnessFunction fitnessFunction, MelodySequence base_seq = null)
        {
            this.fitnessFunction = fitnessFunction;
            this.base_seq = base_seq;
            this.MaxGenerations = 2000;

            if (base_seq != null)
                CreateUniques();

            if (base_seq != null)
            {
                var mark = new MarkovChainGenerator(2);
                mark.AddMelody(base_seq);
                GPCustomTree.generator = mark;
            }
        }
        public MarkovGenerator(MelodySequence[] seqs, PatchNames instrument = PatchNames.Acoustic_Grand)
        {
            this.instrument = instrument;

            int count = seqs.Length;
            note_map = new Dictionary<Note, int>();

            int pitch = 0;
            int j = 0;
            pitches = new int[seqs.Length][];
            foreach (MelodySequence m in seqs)
            {
                Note[] song = m.ToArray();
                pitches[j] = new int[m.Length];

                for (int i = 0; i < song.Length; i++)
                {
                    if (note_map.ContainsKey(song[i]))
                    {

                    }
                    else
                    {
                        note_map[song[i]] = pitch++;
                    }
                    pitches[j][i] = note_map[song[i]];
                }
                j++;
                if (m.Length > max_length)
                    max_length = m.Length;
            }

            hmm = new HiddenMarkovModel(3, pitch+1);
            var teacher = new BaumWelchLearning(hmm);
            teacher.Iterations = 10000;
            teacher.Run(pitches);

            Console.WriteLine("Done training");
        }
 public void SetSequence(MelodySequence sequence)
 {
     this.sequence = sequence;
 }
Exemple #11
0
        public static Composition LoadFromMIDI(string filename)
        {
            Composition comp = new Composition();
            comp.Tracks.Clear();

            NAudio.Midi.MidiFile f = new MidiFile(filename);

              //  if (f.Events.MidiFileType == 1)
               //     return LoadMidiType1(f);

            f.Events.MidiFileType = 0;

            byte max_channels = 0;
            foreach(var trackEvent in f.Events)
            foreach (var e in trackEvent)
                if (e.Channel > max_channels)
                    max_channels = (byte)e.Channel;
            max_channels++;
            Track[] tracks = new Track[max_channels];
            MelodySequence[] seqs = new MelodySequence[max_channels];
            TempoEvent[] tempos = new TempoEvent[max_channels];
            for (byte i = 0; i < max_channels; i++ )
            {
                tracks[i] = new Track(PatchNames.Acoustic_Grand, i);
                seqs[i] = new MelodySequence();
                tempos[i] = new TempoEvent((int)(Note.ToRealDuration((int)Durations.qn, 60) * 1000), 0);
                tempos[i].Tempo = 60;
            }
            foreach(var trackEvents in f.Events)
            foreach (var e in trackEvents)
            {
                if (e as TempoEvent != null)
                {
                    tempos[e.Channel] = (TempoEvent)e;
                }
                if (e as PatchChangeEvent != null)
                {
                    var p = e as PatchChangeEvent;
                    tracks[p.Channel].Instrument = (PatchNames)p.Patch;
                }
                NoteOnEvent on = e as NoteOnEvent;
                if (on != null && on.OffEvent != null)
                {
                    int total_dur = Note.ToNoteLength((int)on.AbsoluteTime, f.DeltaTicksPerQuarterNote, tempos[on.Channel].Tempo);
                    if (total_dur > seqs[on.Channel].Duration)
                        seqs[on.Channel].AddPause(total_dur - seqs[on.Channel].Duration);

                    int duration = Note.ToNoteLength(on.NoteLength, f.DeltaTicksPerQuarterNote, tempos[on.Channel].Tempo);
                    seqs[on.Channel].AddNote(new Note(on.NoteNumber, (int)duration));
                }
            }
            for(byte i = 0; i < max_channels; i++)
            {
                if(seqs[i].Length > 0)
                {
                    tracks[i].AddSequence(seqs[i]);
                    comp.Tracks.Add(tracks[i]);
                }
            }
            comp.NameTag = System.IO.Path.GetFileNameWithoutExtension(filename);
            return comp;
        }
 public ExistingSequenceGenerator(MelodySequence sequence, PatchNames instrument)
 {
     this.sequence = sequence;
     this.instrument = instrument;
 }
Exemple #13
0
 public HarmonySequence GetHarmonySequence(MelodySequence seq)
 {
     HarmonySequence sequence = new HarmonySequence();
     foreach(Note n in seq.ToArray())
     {
         if (n.Pitch > 0 && n.Velocity > 0 && n.Duration > (int)Durations.en)
             sequence.AddChord(GetChord(n));
         else
             seq.AddPause(n.Duration);
     }
     return sequence;
 }
        public Note[] GenerateMelody(MelodySequence inputSeq)
        {
            SampleSet set = new SampleSet();
            var mainNotes = inputSeq.ToArray();

            for (int j = 0; j < mainNotes.Length && j < 200; j++)
            {
                Sample s = GetSample(mainNotes[j],null);

                set.add(s);
            }

            List<Note> notes = new List<Note>();
            var reverseHashes = Utils.ReverseDictionary(noteHashes);
            int mainTime = 0;
            int accompTime = 0;
            foreach (Sample sample in set)
            {
                var res = ComputeNetworkOutput(sample);
                //var maxIndex = GetMaxIndex(res);
                Note outputNote = null;
                if(res[0] <= 0.05)
                    outputNote = new Note(-1, (int)(res[1] * 64.0),0);
                else
                    outputNote = new Note((NoteNames)(res[0] * 12), 4, (Durations)(res[1] * 64.0));
                outputNote.StandardizeDuration();
                notes.Add(outputNote);
             /*   if (reverseHashes.ContainsKey(maxIndex))
                {
                    outputNote = reverseHashes[maxIndex];
                    notes.Add(outputNote);
                    /*accompTime += outputNote.Duration;
                    if (mainTime > accompTime)
                    {
                        notes.Add(new Note(-1, mainTime - accompTime, 0));
                        accompTime += mainTime - accompTime;
                    }
                    mainTime += (int)(sample.getInput()[1] * 64.0);*/
                //}
            }

            return notes.ToArray();
        }
 MelodySequence NormalizeSequence(MelodySequence seq)
 {
     MelodySequence normalized = new MelodySequence();
     foreach(var note in seq)
     {
         Note copy = note.Clone() as Note;
         copy.StandardizeDuration();
         //copy.Octave = 6;
         normalized.AddNote(copy);
     }
     return normalized;
 }
        public void AddMelody(MelodySequence seq)
        {
            Representation.Note[] notes = seq.ToArray();

            chain.Add(notes);
        }
Exemple #17
0
 static void WriteMelodyToFile(MelodySequence seq, string filename)
 {
     Composition comp = new Composition();
     Track track = new Track(PatchNames.Acoustic_Grand, 1);
     track.AddSequence(seq);
     comp.Add(track);
     comp.WriteToMidi(filename);
 }
Exemple #18
0
 static void Play(MelodySequence notes, PatchNames instrument = PatchNames.Vibraphone)
 {
     MusicPlayer player = new MusicPlayer();
     player.SetPatch((int)instrument, 1);
     player.Play(notes);
     player.Close();
 }
 public void AddMelodySequence(MelodySequence seq)
 {
     foreach (Note n in seq.ToArray())
         AddNote(n);
 }
        private Track AddPercussionTrack(MelodySequence seq, INoteGenerator gen)
        {
            Track t = new Track(gen.Instrument, 10);

            for(int i  = 0 ; i < ActiveComposition.Tracks.Count; i++)
            {
                var ctrack = ActiveComposition.Tracks[i];
                if(ctrack.Channel == 10)
                {
                    ctrack.Clear();
                    ActiveComposition.Tracks.RemoveAt(i);
                    break;
                }
            }

            t.AddSequence(seq);
            ActiveComposition.Tracks.Add(t);
            generators.Add(gen);
            if (OnCompositionChange != null)
                OnCompositionChange(this, new EventArgs());
            return t;
        }
Exemple #21
0
        public MelodySequence Generate()
        {
            int seed = random.Next();

            var gen_mel = new MelodySequence(chain.Chain(MaxNotes, seed));

            return gen_mel;
        }
        public Note[] GenerateMelody(MelodySequence inputSeq)
        {
            SampleSet set = new SampleSet();
            var mainNotes = inputSeq.ToArray();

            for (int j = INPUT_NOTES; j < mainNotes.Length && j < 200; j++)
            {
                Note[] prevNotes = new Note[INPUT_NOTES];
                for(int k = 0; k < INPUT_NOTES; k++)
                {
                    prevNotes[INPUT_NOTES - k-1] = mainNotes[j - k];
                }
                Sample s = GetSample(prevNotes, null);

                set.Add(s);
            }

            List<Note> notes = new List<Note>();
            var reverseHashes = Utils.ReverseDictionary(noteHashes);
            int mainTime = 0;
            int accompTime = 0;

            int i = 0;
            foreach (Sample sample in set)
            {

                var res = network.Compute(sample.Inputs);
                //Note n = new Note((NoteNames)((int)(res[0] * 12)), 6, (Durations)((int)(res[1] * 64.0)));
                Note n = new Note((int)(res[0] * 128), (int)(res[1] * 64.0));
                n.Duration *= 2;
                n.StandardizeDuration();
                if (mainTime >= accompTime)
                {
                    notes.Add(n);
                    accompTime += (int)n.Duration;
                }

                if(i++ % 20 == 0)
                {
                    notes.Add(new Note(-1, mainTime - accompTime));
                }
                mainTime += (int)(sample.Inputs[1] * 64);

            }

            return notes.ToArray();
        }
 public object Clone()
 {
     MelodySequence seq = new MelodySequence();
     foreach (Note n in sequence)
         seq.AddNote(n.Clone() as Note);
     return seq;
 }
 /// <summary>
 /// Creates a new Melody Sequence for each n notes
 /// </summary>
 /// <param name="n">Period of notes</param>
 /// <returns></returns>
 public MelodySequence[] Split(int n)
 {
     List<MelodySequence> sequences = new List<MelodySequence>();
     for(int i = 0; i < sequence.Count - n; i+=n)
     {
         MelodySequence seq = new MelodySequence();
         for(int j = 0; j < n; j++)
         {
             seq.AddNote(this.sequence[i + j]);
         }
         sequences.Add(seq);
     }
     return sequences.ToArray();
 }
Exemple #25
0
        static void Main(string[] args)
        {
            /*Feed forward neural network
            Group notes into 3
            Classify all groups in existing songs as 1, all other combinations as 0.

            Use as fitness function

            Use HMM decode as fitness function GA*/

               /* Databank db = new Databank("lib");

            List<MelodySequence> drumSeqs = new List<MelodySequence>();
            var comps = new Composition[][] { db.Load("Classic Rock").Compositions, db.Load("Jazz").Compositions, Utils.LoadCompositionsParallel(@"D:\Sync\4th year\Midi\Library2\Drums") };

            foreach(Composition[] catt in comps)
            {
                foreach(var c in catt)
                {
                    foreach(var t in c.Tracks)
                    {
                        if(t.Channel == 10)
                        {
                            drumSeqs.Add(t.GetMainSequence() as MelodySequence);
                        }
                    }
                }
            }

            List<Composition> drums = new List<Composition>();
            foreach(var m in drumSeqs)
            {
                Composition c = new Composition();
                Track t = new Track(PatchNames.Acoustic_Grand, 10);
                t.AddSequence(m);
                c.Add(t);
                drums.Add(c);
            }

            var catdrum = new CompositionCategory("Drums", "lib/Drums", drums.ToArray());
            catdrum.Save("lib/Drums");
            Console.ReadLine();
            */

            /*Composition comp = Composition.LoadFromMIDI(@"C:\Users\1gn1t0r\Documents\git\GeneticMIDI\GeneticMIDI\bin\Debug\test\other\twinkle.mid");
            float time = Note.ToRealDuration(comp.GetLongestTrack().Duration);
            Console.WriteLine("Total time: {0}", time);
            MusicPlayer player = new MusicPlayer();
            player.Play(comp);
            Console.ReadLine();*/

            var twink = Composition.LoadFromMIDI(@"C:\Users\1gn1t0r\Documents\git\GeneticMIDI\GeneticMIDI\bin\Debug\test\other\twinkle.mid");

               Databank db = new Databank("lib");
            var cat = db.Load("Jazz");

            Codebook<Note> book = new Codebook<Note>();

            List<int[]> sequences = new List<int[]>();

            foreach(var comp in cat.Compositions)
            {
                foreach(var track in comp.Tracks)
                {
                    if(track.Instrument == PatchNames.Trumpet)
                    {
                        var mel = track.GetMelodySequence();
                        mel.Trim(80);
                        mel.StandardizeDuration();

                        book.Add(mel.Notes);
                        sequences.Add(book.ToCodes(mel.Notes));
                    }
                }
                if (sequences.Count > 10)
                    break;
            }

            DotNetLearn.Markov.HiddenMarkovModel hmm = new DotNetLearn.Markov.HiddenMarkovModel(60, book.TotalUniqueSymbols);
            hmm.UniformRandomPriors();
            hmm.MaxIterations = 50;
            hmm.Train(sequences.ToArray());

            var o = hmm.PredictObservationSequence(80);
            var newmel = new MelodySequence(book.Translate(o));

            Track t = new Track(PatchNames.Trumpet, 2);
            t.AddSequence(newmel);

            Console.ReadLine();
            MusicPlayer player = new MusicPlayer();
            player.Play(t);

            player.Stop();

            Console.ReadLine();

            /*
            var gen = new SamplingWithReplacement(cat, PatchNames.Acoustic_Grand);

            var mel = gen.Generate();

            Console.WriteLine(mel.ToString());
            MusicPlayer player = new MusicPlayer();
            player.Play(mel);

            Console.WriteLine("Press enter to save");
            Console.ReadLine();
            WriteMelodyToFile(gen.OriginalSequence, "sampling_in.mid");
            WriteMelodyToFile(mel, "sampling_out.mid");
            */

                /*  MusicPlayer player = new MusicPlayer();

                  //db.LoadAll();

                  AccompanyGeneratorMarkov genMark = new AccompanyGeneratorMarkov(cat);
                  var targetSeq = cat.Compositions[2].GetLongestTrack().GetMainSequence() as MelodySequence;
                  var seqTest = genMark.Generate(targetSeq,5);

                  Track trackTest = new Track(PatchNames.Orchestral_Strings, 2); trackTest.AddSequence(seqTest);

                  Track targetTrack = new Track(PatchNames.Acoustic_Grand, 3); targetTrack.AddSequence(targetSeq);

                  Composition comp = new Composition();
                  comp.Add(trackTest);
                  comp.Add(targetTrack);

                  player.Play(comp);

                  return;*/

                /*   Databank db = new Databank("lib");
                   var cat = db.Load("Classical");
                   //AccompanimentGenerator2 Test
                   AccompanimentGenerator2 gen = new AccompanimentGenerator2(cat, PatchNames.Orchestral_Strings);
                   gen.Train();
                   //
                   Composition comp = Composition.LoadFromMIDI(@"D:\Sync\4th year\Midi\Library2\Classical\Mixed\dvorak.mid");
                   //var comp = Composition.LoadFromMIDI(@"C:\Users\1gn1t0r\Documents\git\GeneticMIDI\GeneticMIDI\bin\Debug\test\ff7tifa.mid");
                   gen.SetSequence(comp.Tracks[0].GetMainSequence() as MelodySequence);

                   MusicPlayer player = new MusicPlayer();

                       Console.WriteLine("Press enter to listen");
                       Console.ReadLine();

                       var mel = gen.Generate();
                       Composition newComp = new Composition();
                       Track newTrack = new Track(PatchNames.Orchestral_Strings , 2);
                       newTrack.AddSequence(mel);
                       newComp.Add(newTrack);
                       /*comp.Tracks[0].Instrument = PatchNames.Acoustic_Grand; (comp.Tracks[0].GetMainSequence() as MelodySequence).ScaleVelocity(0.8f);
                       /* newComp.Tracks.Add(comp.Tracks[0]);

                       player.Play(newComp);*/

                Console.ReadLine();
        }
Exemple #26
0
        public MelodySequence Generate(MelodySequence seq)
        {
            MelodySequence seqOut = new MelodySequence();

            var hashedNotes = hmm.Generate(100);
            //double trouble = 0;
            //var hashedNotes = hmm.Decode(GetHashes(seq.ToArray()), out trouble);
            seqOut.AddNotes(book.Translate(hashedNotes));

            return seqOut;
        }
Exemple #27
0
        static void Test8()
        {
            MusicPlayer player = new MusicPlayer();

            Console.WriteLine("Hidden Markov Model");
            var m1 = GetMelodySequence(@"test\other\frere.mid");
            var m2 = GetMelodySequence(@"test\other\babaa.mid");
            var m3 = GetMelodySequence(@"test\other\twinkle.mid");

            var m4 = GetMelodySequence(@"test\hagrid.mid");
            var m5 = GetMelodySequence(@"test\harry.mid");
            var m6 = GetMelodySequence(@"test\harry2.mid");
            MarkovGenerator markov = new MarkovGenerator(new MelodySequence[] { m6 });
            while (true)
            {
                Composition comp = new Composition();

                GeneticGenerator gen = new GeneticGenerator(new MetricSimilarity(m6, new IMetric[] { new Rhythm(), new RhythmicBigram(), new RhythmicInterval() }));
                var notes2 = gen.Generate();
                Track t2 = new Track((PatchNames)0, 10);
                MelodySequence s = new MelodySequence();
                s.AddPause((int)Durations.wn * 10);
                foreach (Note n in notes2.Notes)
                {
                    if (n.Pitch <= 0)
                        n.Pitch = 0;
                    else if (n.Pitch > 48)
                        n.Pitch = 40;
                    else if (n.Pitch > 70)
                        n.Pitch = 35;
                    else
                    {
                        n.Pitch = 49;
                        n.Duration *= 4;
                        n.Velocity = 50;
                        s.AddPause(n.Duration * 2);
                    }
                    s.AddNote(n);
                }
                t2.AddSequence(s);

                var notes3 = markov.Generate().Notes as Note[];

                MelodySequence baseseq = new MelodySequence();

                int max_dur = 0;
                int max_index = 0;
                for (int i = (int)(notes3.Length * 0.7f); i < notes3.Length; i++)
                {
                    if (notes3[i].Duration > max_dur)
                    {
                        max_dur = notes3[i].Duration;
                        max_index = i;
                    }
                }
                Note last_note = null;
                for (int i = 0; i < max_index; i++)
                {
                    last_note = notes3[i];
                    baseseq.AddNote(last_note);
                }
                baseseq.AddNote(new Note(last_note.Pitch - 12, last_note.Duration));
                baseseq.AddNote(new Note(last_note.Pitch - 24, last_note.Duration * 2));
                baseseq.AddPause(last_note.Duration * 32);

                Track t = new Track(PatchNames.Vibraphone, 1);

                var b1 = baseseq.Clone() as MelodySequence;
                var b2 = baseseq.Clone() as MelodySequence;
                var b3 = baseseq.Clone() as MelodySequence;
                b1.Transpose(12);
                b2.Transpose(6);
                b3.Transpose(-12);
                t.AddSequence(baseseq);
                t.AddSequence(b1);
                t.AddSequence(b2);
                t.AddSequence(b3);

                comp.Add(t);
                comp.Add(t2);
                Console.WriteLine("Press enter key to listen");
                Console.ReadLine();
                player.Play(comp);
            }
        }
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Composition comp;
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            dlg.DefaultExt = ".mid";
            dlg.Filter = "MIDI Files (*.mid)|*.mid";
            dlg.Title = "Load MIDI file";

            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                comp = Composition.LoadFromMIDI(dlg.FileName);

                TrackSelector trackSel = new TrackSelector(comp);
                if(trackSel.ShowDialog() == true)
                {
                    this.GeneratedSequence = trackSel.SelectedSequence;
                    this.Instrument = trackSel.SelectedInstrument;
                    this.Generator = new ExistingSequenceGenerator(this.GeneratedSequence, this.Instrument);
                    this.DialogResult = true;
                    this.Close();
                }
            }
        }
        public MelodySequence Generate()
        {
            var mel = GetRandomMelody();
            OriginalSequence = mel;
            var notes = mel.ToArray();

            var possibleDurations = Enum.GetValues(typeof(Durations)).Cast<Durations>().ToArray();

            Note[] newNotes = new Note[notes.Length];
            Array.Copy(notes, newNotes, notes.Length);

            double originalProb = model.EvaluateLogProbability(notes);
            double prevProb = originalProb;

            int minPitch = (int)(averagePitch - stdPitch); if (minPitch < 0) minPitch = 0;
            int maxPitch = (int)(averagePitch + stdPitch); if (maxPitch > 127) maxPitch = 127;

            var possibleNotes = model.GetPossibleItemClasses();

            int iter = 0;
            //for (int i = 0; i < notes.Length; i++)
            while(true)
            {
                int i = random.Next(notes.Length);

                Console.WriteLine("Progress: {0} / {1}  --  OldProb {2}, NewProb {3}", iter, MaxIterations, originalProb, prevProb);
                foreach (Note newNote in possibleNotes)
                {
                    //var newNote = new Note((int)pitch, (int)dur);

                    Note[] tempNotes = new Note[notes.Length];
                    Array.Copy(newNotes, tempNotes, notes.Length);

                    tempNotes[i] = newNote;

                    double newProb = model.EvaluateLogProbability(tempNotes);
                    if (newProb >= prevProb)
                    {
                        prevProb = newProb;
                        newNotes[i] = newNote;
                    }
                }
                if (iter >= MaxIterations)
                    break;

                if (OnProgressChange != null)
                    OnProgressChange(iter, MaxIterations, prevProb);

                iter++;
            }

            double finalProb = model.EvaluateLogProbability(newNotes);

            return new MelodySequence(newNotes);
        }
        private void Generate()
        {
            int index = optionsTab.SelectedIndex;

            progressGenSlider.Value = 0;

            if (index == 0)
            {
                if (geneticInstrumentBox.SelectedItem == null)
                    return;

                fitnessPlot.ResetAllAxes();
                SetupLinePlot(fitnessPlot, "Average Fitness");
                (fitnessPlot.Model.Series[0] as LineSeries).Points.Clear();
                fitnessPlot.Model.Series[0].Unselect();
                fitnessPlot.InvalidatePlot();

                //GA
                IFitnessFunction fitness = null;

                //Options
                List<IMetric> activeMetrics = new List<IMetric>();
              //  if (metricChromaticTone.IsChecked == true)
              //      activeMetrics.Add(new ChromaticTone());
                if (metricChromaticToneDistance.IsChecked == true)
                    activeMetrics.Add(new ChromaticToneDistance());
                if (metricChromaticToneDuration.IsChecked == true)
                    activeMetrics.Add(new ChromaticToneDuration());
                if (metricMelodicBigram.IsChecked == true)
                    activeMetrics.Add(new MelodicBigram());
                if (metricMelodicInterval.IsChecked == true)
                    activeMetrics.Add(new MelodicInterval());
             //   if (metricPitch.IsChecked == true)
             //       activeMetrics.Add(new Pitch());
            //    if (metricPitchDistance.IsChecked == true)
             //       activeMetrics.Add(new PitchDistance());
            //    if (metricRhythm.IsChecked == true)
            //        activeMetrics.Add(new Rhythm());
                if (metricRhythmicBigram.IsChecked == true)
                    activeMetrics.Add(new RhythmicBigram());
                if (metricRhythmicInterval.IsChecked == true)
                    activeMetrics.Add(new RhythmicInterval());

                fitness = GeneticMIDI.FitnessFunctions.MetricSimilarity.GenerateMetricSimilarityMulti(category.Compositions, activeMetrics.ToArray(), GeneticMIDI.FitnessFunctions.SimilarityType.Cosine);
                /*
                if (fitnessFuncCombo.SelectedIndex == 0)
                    fitness = new GeneticMIDI.FitnessFunctions.MetricSimilarity(seq, activeMetrics.ToArray(), GeneticMIDI.FitnessFunctions.SimilarityType.Cosine);
                if (fitnessFuncCombo.SelectedIndex == 1)
                    fitness = new GeneticMIDI.FitnessFunctions.MetricSimilarity(seq, activeMetrics.ToArray(), GeneticMIDI.FitnessFunctions.SimilarityType.Euclidian);
                if (fitnessFuncCombo.SelectedIndex == 2)
                    fitness = new GeneticMIDI.FitnessFunctions.MetricSimilarity(seq, activeMetrics.ToArray(), GeneticMIDI.FitnessFunctions.SimilarityType.Pearson);
                if (fitnessFuncCombo.SelectedIndex == 3)
                    fitness = new GeneticMIDI.FitnessFunctions.CrossCorrelation(seq);
                if (fitnessFuncCombo.SelectedIndex == 4)
                    fitness = GeneticMIDI.FitnessFunctions.NCD.FromMelodies(category);*/

                Instrument = (PatchNames)geneticInstrumentBox.SelectedItem;

                var gen = new GeneticGenerator(fitness, Instrument, category);
                gen.OnPercentage += gen_OnPercentage;

                gen.MaxGenerations = (int)maxGenerationSlider.Value;
                Generator = gen;

                new Thread(() =>
                {
                    var notes = gen.Generate();

                    var mel = notes;
                    GeneratedSequence = mel;
                    progressGenSlider.Dispatcher.Invoke(() =>
                    {
                        progressGenSlider.Value = 100;
                    });
                }).Start();
            }
            if (index == 1)
            {
                if (instrBox.SelectedItem as ListBoxItem == null || (instrBox.SelectedItem as ListBoxItem).Tag == null)
                    return;
                if ((int)((instrBox.SelectedItem as ListBoxItem).Tag) == -1)
                {
                    // Drum Generator
                    DrumGenerator gen = new DrumGenerator();

                    Generator = gen;

                    Instrument = PatchNames.Helicopter;

                    new Thread(() =>
                    {
                            StartSpinner();
                            gen.Initialize(new Databank(GeneticMIDI.Constants.LOCAL_LIBRARY_PATH));
                            GeneratedSequence = gen.Generate();
                            StopSpinner();

                        progressGenSlider.Dispatcher.Invoke(() =>
                        {
                            progressGenSlider.Value = 100;
                        });

                    }).Start();

                }
                else
                {
                    PatchNames instrument = (PatchNames)((instrBox.SelectedItem as ListBoxItem).Tag);
                    Instrument = instrument;

                    InstrumentalGenerator gen = Generator as InstrumentalGenerator;
                    if (gen == null)
                        return;

                    gen.SetInstrument(Instrument);

                    new Thread(() =>
                    {
                        if (gen.IsInitialized)
                        {
                            StartSpinner();
                            GeneratedSequence = gen.GenerateInstrument(instrument);
                            StopSpinner();
                        }

                        progressGenSlider.Dispatcher.Invoke(() =>
                        {
                            progressGenSlider.Value = 100;
                        });

                    }).Start();
                }
            }
            if(index == 2)
            {
                if (accompInstruBox.Items.Count == 0 || accompTrackBox.Items.Count == 0)
                    return;
                Instrument = (PatchNames)(accompInstruBox.SelectedItem);
                Track track = (accompTrackBox.SelectedItem as ListBoxItem).Tag as Track;

                var melSeq = track.GetMainSequence() as MelodySequence;
                Random rnd = new Random();
                if(accompMethoBox.SelectedIndex == 0)
                {
                    AccompanyGeneratorMarkov gen = new AccompanyGeneratorMarkov(category, Instrument);
                    Generator = gen;
                    new Thread(() =>
                        {

                            StartSpinner();
                            GeneratedSequence = gen.Generate(melSeq,rnd.Next());
                            StopSpinner();
                            progressGenSlider.Dispatcher.Invoke(() =>
                            {
                                progressGenSlider.Value = 100;
                            });
                        }).Start();
                }
                else if (accompMethoBox.SelectedIndex == 1)
                {
                    AccompanimentGeneratorANNFF gen = new AccompanimentGeneratorANNFF(category, Instrument);
                    Generator = gen;
                    gen.SetSequence(melSeq);
                    new Thread(() =>
                        {

                            StartSpinner();
                            gen.Load();
                            GeneratedSequence = gen.Generate();

                            StopSpinner();
                            progressGenSlider.Dispatcher.Invoke(() =>
                                {
                                    progressGenSlider.Value = 100;
                                });

                        }).Start();
                }

            }
            if(index == 3)
            {
                //stochasticLogPlot.Model.Series.Clear();
                stochasticLogPlot.ResetAllAxes();
                SetupLinePlot(stochasticLogPlot, "Log Likelihood");
                (stochasticLogPlot.Model.Series[0] as LineSeries).Points.Clear();
                stochasticLogPlot.Model.Series[0].Unselect();
                stochasticLogPlot.InvalidatePlot();

                if (loadInstrument.SelectedItem == null)
                    return;
                Instrument = (PatchNames)(loadInstrument.SelectedItem);

                SamplingWithReplacement swr = new SamplingWithReplacement(category, Instrument);
                swr.OnProgressChange += swr_OnProgressChange;
                swr.MaxIterations = (int)loadGenerationsSlider.Value;

                Generator = swr;

                new Thread(() =>
                {
                    StartSpinner();
                    GeneratedSequence = swr.Generate();
                    StopSpinner();
                    progressGenSlider.Dispatcher.Invoke(() =>
                    {
                        progressGenSlider.Maximum = 100;
                        progressGenSlider.Value = 100;
                    });

                }).Start();

            }
            if(index == 4)
            {
                if (randomInstrument.SelectedItem == null)
                    return;
                Instrument = (PatchNames)randomInstrument.SelectedItem;

                int centralNotePitch = (int)randomOctave.Value * 12;
                int noteShift = (int)randomPitchVar.Value;
                int minNote = centralNotePitch - noteShift;
                int maxNote = centralNotePitch + noteShift;
                if (minNote <= 0)
                    minNote = 1;
                if (maxNote >= 127)
                    maxNote = 126;
                int durMin = (int)Math.Pow(randomDurationRange.LowerValue, 2);
                int durMax = (int)Math.Pow(randomDurationRange.UpperValue, 2);
                int length = (int)randomLength.Value;

                ScaleType scale = randomScale.SelectedItem as ScaleType;

                var gen = new ReflectingBrownNoteGenerator(new NoteRangeRestrictor(minNote, maxNote, durMin, durMax, scale), new Random(), -2, 2, -1, 1, Instrument);
                Generator = gen;
                gen.MaxNotes = length;

                new Thread(() =>
                {
                    StartSpinner();
                    GeneratedSequence = gen.Generate();
                    StopSpinner();
                    progressGenSlider.Dispatcher.Invoke(() =>
                    {
                        progressGenSlider.Value = 100;
                    });

                }).Start();

                Console.ReadLine();
            }
        }