// This returns the patch names from the PNAMES lump // A directory resource does not support this lump, but the wads in the directory may contain this lump public override PatchNames LoadPatchNames() { PatchNames pnames; // Error when suspended if (issuspended) { throw new Exception("Data reader is suspended"); } // Load from wad files // Note the backward order, because the last wad's images have priority for (int i = wads.Count - 1; i >= 0; i--) { pnames = wads[i].LoadPatchNames(); if (pnames != null) { return(pnames); } } // If none of the wads provides patch names, let's see if we can string pnamesfile = FindFirstFile("PNAMES", false); if ((pnamesfile != null) && FileExists(pnamesfile)) { MemoryStream pnamesdata = LoadFile(pnamesfile); pnames = new PatchNames(pnamesdata); pnamesdata.Dispose(); return(pnames); } return(null); }
public SamplingWithReplacement(CompositionCategory cat, PatchNames instrument) { this.MaxIterations = 200; this.MaxLength = 100; this.instrument = instrument; this.category = cat; random = new SimpleRNG(); random.SetSeedFromSystemTime(); model = new MarkovChain<Note>(1); foreach(var comp in cat.Compositions) { foreach(var track in comp.Tracks) { if (!IsValidTrack(track)) continue; var mel = (track.GetMainSequence() as MelodySequence).Clone() as MelodySequence; mel.StandardizeDuration(); model.Add(mel.ToArray()); break;//only first track } } CalculateStats(); }
public HMMGenerator(PatchNames instrument) { this.book = new Codebook<Note>(); this.instrument = instrument; DotNetLearn.Data.SampleSet asdasd; Accord.Math.Tools.SetupGenerator(10); // Consider some phrases: // string[][] phrases = { "The Big Brown Fox Jumps Over the Ugly Dog".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), "This is too hot to handle".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), "I am flying away like a gold eagle".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), "Onamae wa nan desu ka".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), "And then she asked, why is it so small?".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), "Great stuff John! Now you will surely be promoted".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), "Jayne was taken aback when she found out her son was gay".Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries), }; // Let's begin by transforming them to sequence of // integer labels using a codification codebook: var codebook = new Codification("Words", phrases); // Now we can create the training data for the models: int[][] sequence = codebook.Translate("Words", phrases); // To create the models, we will specify a forward topology, // as the sequences have definite start and ending points. // var topology = new Forward(states: codebook["Words"].Symbols); int symbols = codebook["Words"].Symbols; // We have 7 different words // Create the hidden Markov model HiddenMarkovModel hmm = new HiddenMarkovModel(topology, symbols); // Create the learning algorithm var teacher = new ViterbiLearning(hmm); // Teach the model about the phrases double error = teacher.Run(sequence); // Now, we can ask the model to generate new samples // from the word distributions it has just learned: // List<int> sample = new List<int>(); int count = 10; sample.Add(hmm.Generate(1)[0]); while(sample.Count < count) { var k = hmm.Predict(sample.ToArray(), 1); sample.AddRange(k); } // And the result will be: "those", "are", "words". string[] result = codebook.Translate("Words", sample.ToArray()); }
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 PlaybackMessage(PatchNames patch, byte channel_) { message = PlaybackMessageType.Patch; velocity = (byte)patch; channel = channel_; pitch = 0; duration = 0; tag = null; }
public ReflectingBrownNoteGenerator( NoteRangeRestrictor nrr, Random randGen, int lowestPitchChange, int highestPitchChange, int lowestLengthStep, int highestLengthStep, PatchNames instrument = PatchNames.Acoustic_Grand) : base(nrr, lowestPitchChange, highestPitchChange, lowestLengthStep, highestLengthStep) { this.instrument = instrument; this.MaxNotes = 200; gen = randGen; }
public GeneticGenerator(IFitnessFunction fitnessFunction, PatchNames instrument = PatchNames.Acoustic_Grand, CompositionCategory cat=null) { this.fitnessFunction = fitnessFunction; this.cat = cat; this.MaxGenerations = 1000; this.PrintProgress = true; this.instrument = instrument; if (cat != null) { // Markov generator var mark = new MarkovChainGenerator(instrument, 2); // Allowed notes HashSet<Durations> durs = new HashSet<Durations>(); HashSet<int> fullPitches = new HashSet<int>(); foreach(var c in cat.Compositions) { if (c.Tracks.Count < 1) continue; var cloneMel = (c.Tracks[0].GetMainSequence() as MelodySequence).Clone() as MelodySequence; cloneMel.StandardizeDuration(); mark.AddMelody(cloneMel); foreach (var n in cloneMel.Notes) { durs.Add(NoteGene.GetClosestDuration(n.Duration)); fullPitches.Add(n.Pitch); } avgLength += cloneMel.Length; } avgLength /= cat.Compositions.Length; GPCustomTree.generator = mark; NoteGene.AllowedDurations = durs.ToArray(); NoteGene.AllowedFullPitches = fullPitches.ToArray(); } }
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"); }
static void Play(IEnumerable<Note> notes, PatchNames instrument = PatchNames.Vibraphone) { MusicPlayer player = new MusicPlayer(); player.SetPatch((int)instrument, 1); player.PlayNotes(notes); player.Close(); }
public Track(PatchNames instrument, byte channel) { this.Instrument = instrument; this.Channel = channel; sequences = new List<ISequence>(); }
public AccompanimentGeneratorANNFF(CompositionCategory category, PatchNames instrument) { this.Epochs = 50000; this.category = category; this.instrument = instrument; }
public AccompanimentGenerator(CompositionCategory category, PatchNames instrument) { this.category = category; this.instrument = instrument; }
public ExistingSequenceGenerator(MelodySequence sequence, PatchNames instrument) { this.sequence = sequence; this.instrument = instrument; }
public MelodySequence GenerateInstrument(PatchNames patch) { Random r = new Random(); int randomSeed = r.Next(); return GenerateInstrument(patch, randomSeed); }
public TrackGenerator(CompositionCategory category, Composition comp) { this.category = category; InitializeComponent(); // Load data for accompany instruments string path = "save/" + category.CategoryName; if(System.IO.Directory.Exists(path)) { var files = System.IO.Directory.GetFiles(path); foreach(var file in files) { try { string filename = System.IO.Path.GetFileNameWithoutExtension(file); if (!filename.ToLower().Contains("accomp_ann_ff_")) continue; var sub = filename.Substring(14); PatchNames instrument = (PatchNames)(int.Parse(sub)); if(!accompInstruBox.Items.Contains(instrument)) accompInstruBox.Items.Add(instrument); } catch(Exception E) { Console.WriteLine(E); } } } // Load data for accompany tracks if(comp != null) for(int i = 0; i < comp.Tracks.Count; i++) { var track = comp.Tracks[i]; ComboBoxItem item = new ComboBoxItem(); item.Content = string.Format("Track {0} - {1}", i.ToString(), track.Instrument.ToString()); item.Tag = track; accompTrackBox.Items.Add(item); } randomScale.Items.Clear(); foreach(var s in Scales.ScaleTypes) { //ListBoxItem item = new ListBoxItem(); randomScale.Items.Add(s); } randomInstrument.Items.Clear(); var popularInstruments = new PatchNames[]{PatchNames.Acoustic_Grand,PatchNames.String_Ensemble_1, PatchNames.Acoustic_Bass,PatchNames.Trumpet,PatchNames.Violin,PatchNames.Electric_Grand, PatchNames.French_Horn,PatchNames.Flute,PatchNames.Trombone,PatchNames.Acoustic_Guitarnylon, PatchNames.Orchestral_Strings}; foreach (var d in popularInstruments) { loadInstrument.Items.Add(d); geneticInstrumentBox.Items.Add(d); randomInstrument.Items.Add(d); } StopSpinner(); LoadInstrumentalData(); }
public MelodySequence GenerateInstrument(PatchNames patch, int seed) { lastInstrument = patch; var chain = instruments[patch]; return new MelodySequence(chain.Chain(MaxNotes,seed)); }
public void SetInstrument(PatchNames instrument) { this.lastInstrument = instrument; }
// This loads the textures public override ICollection <ImageData> LoadTextures(PatchNames pnames) { Dictionary <long, ImageData> images = new Dictionary <long, ImageData>(); ICollection <ImageData> collection; List <ImageData> imgset = new List <ImageData>(); // Error when suspended if (issuspended) { throw new Exception("Data reader is suspended"); } // Load from wad files (NOTE: backward order, because the last wad's images have priority) for (int i = wads.Count - 1; i >= 0; i--) { collection = wads[i].LoadTextures(pnames); AddImagesToList(images, collection); } // Should we load the images in this directory as textures? if (roottextures) { collection = LoadDirectoryImages("", ImageDataFormat.DOOMPICTURE, false); AddImagesToList(images, collection); } // Add images from texture directory collection = LoadDirectoryImages(TEXTURES_DIR, ImageDataFormat.DOOMPICTURE, true); AddImagesToList(images, collection); // Load TEXTURE1 lump file imgset.Clear(); string texture1file = FindFirstFile("TEXTURE1", false); if ((texture1file != null) && FileExists(texture1file)) { MemoryStream filedata = LoadFile(texture1file); WADReader.LoadTextureSet("TEXTURE1", filedata, ref imgset, pnames); filedata.Dispose(); } // Load TEXTURE2 lump file string texture2file = FindFirstFile("TEXTURE2", false); if ((texture2file != null) && FileExists(texture2file)) { MemoryStream filedata = LoadFile(texture2file); WADReader.LoadTextureSet("TEXTURE2", filedata, ref imgset, pnames); filedata.Dispose(); } // Add images from TEXTURE1 and TEXTURE2 lump files AddImagesToList(images, imgset); // Load TEXTURES lump file imgset.Clear(); string[] alltexturefiles = GetAllFilesWithTitle("", "TEXTURES", false); foreach (string texturesfile in alltexturefiles) { MemoryStream filedata = LoadFile(texturesfile); WADReader.LoadHighresTextures(filedata, texturesfile, ref imgset, images, null); filedata.Dispose(); } // Add images from TEXTURES lump file AddImagesToList(images, imgset); // Add images to the container-specific texture set foreach (ImageData img in images.Values) { textureset.AddImage(img); } return(new List <ImageData>(images.Values)); }
public AccompanyGeneratorMarkov(CompositionCategory cat, PatchNames instrument) { this.instrument = instrument; Add(cat); }
MelodySequence GenerateInstrument(PatchNames patch, int seed) { var chain = instruments[patch]; return new MelodySequence(chain.Chain(100,seed)); }
public MarkovChainGenerator(PatchNames instrument, int order = 3, int length = 150) { this.instrument = instrument; this.chain = new MarkovChain<Note>(order); this.MaxLength = length; }
static void TrainANNFFAccomp() { Console.WriteLine("This application trains accompaniment neural networks"); var cats = Databank.GetCategories(); Databank db = new Databank("lib"); var popularInstruments = new PatchNames[]{PatchNames.Acoustic_Grand,PatchNames.String_Ensemble_1, PatchNames.Acoustic_Bass,PatchNames.Trumpet,PatchNames.Vibraphone,PatchNames.Electric_Grand, PatchNames.French_Horn,PatchNames.Flute,PatchNames.Trombone,PatchNames.Music_Box}; foreach (var catName in cats) { Console.WriteLine("Category {0}", catName); var cat = db.Load(catName); if (cat.Compositions.Length > 3000) Console.WriteLine("Skipping category {0} due to length", cat.CategoryName); foreach (var instr in popularInstruments) { Console.WriteLine("Training ANN for {0} - {1}, {2} epochs", cat.ToString(), instr.ToString(), 6000); try { AccompanimentGeneratorANNFF ann = new AccompanimentGeneratorANNFF(cat, instr); ann.Epochs = 5000; ann.Train(); } catch (Exception e) { Console.WriteLine(e.Message); } } } Console.ReadLine(); }
static void Play(MelodySequence notes, PatchNames instrument = PatchNames.Vibraphone) { MusicPlayer player = new MusicPlayer(); player.SetPatch((int)instrument, 1); player.Play(notes); player.Close(); }
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(); } } }
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(); } }
void listBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e) { Track track = (sender as ListBoxItem).Tag as Track; this.SelectedSequence = track.GetMainSequence() as MelodySequence; this.SelectedInstrument = track.Instrument; this.DialogResult = true; this.Close(); }