/* Program Finch. Version: 16/II/2018. This is a musical project of the EvolJava Community. It is our solution to a challenge in Vol VIII of the series Java for the Study of Evolution www.evoljava.com Download the Finch.zip file and import it into NetBeans. You need NetBeans with Java 8 and JavaFX. To learn JavaFX you can go through the area Morphology and fossils at our site www.evoljava.com License for this and all our software: unconditional. The name of this application comes from a species of singer birds, whose males sing to invite females, say, to a source of food. Darwin registered the evolution of finches in the sense that relative frequencies of diverse species were shifted by ecological factors. So, finches played an important role in the gestation of the Evolutionary Theory in the mind of Darwin. We consider that this example of evolution is wonderful and that it is licit to convert examples into theories. But, we consider inappropriate to convert theories into dogmas specially when these are obviously false. In fact, our purpose is to build a rich platform of knowledge upon which the falsity of the Evolutionary Theory becomes self-evident and self-reinforcing under deeper investigation. With this program you can play simple abc tunes, listen at the sound of ADN and proteins, train you ear and made evolution into a composer. To learn abc notation and to get tunes go to: http://abcnotation.com/learn The User can also test the First theory of music: All notes are pleasant separately and so are when they form strings. Predictions: 1) Notes concatenated at random are pleasant. 2) Every string is musical, DNA included. We test the theory through generation of tunes produced by random notes else by DNA or a protein sequence that must be pasted to the text area. For random notes we use the inbuilt Java generator of random numbers. The program also can play a simple ABC tune (with just one voice) and show its score. The program includes a training facility for pitch recognizing and for keeping record of user's performance. Musical analysis is done following the Statistical Theory of music, (a correction to the First Theory): Frequencies of notes in a tune are counted and the corresponding table is given to feed the random generator. */ /* ===== ABOUT PACKAGE abc========== The package abc uses abc-notation to encode music for Java. The notation is both natural and smart. The package abc is in the JAR (Java ARchive) file: abc4j_v05.jar By September/2017 this file can be downloaded from https://code.google.com/archive/p/abc4j/downloads else write to me: jose@evoljava.com. (in case of need, it will be posted at evoljava.com) To add the jar file to the NetBeans project: right click over the name of the project under the projects' tab. Choose Properties -> Libraries -> compile -> Add jar/Folder -> your jar file -> End. */ package finch; import abc.midi.TunePlayer; import abc.notation.Tune; import abc.parser.TuneBook; import abc.parser.TuneParser; import abc.ui.swing.JScoreComponent; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ObservableValue; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TextInputDialog; import javafx.scene.image.ImageView; import javafx.scene.input.MouseButton; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Stop; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.StageStyle; import javax.swing.JFrame; import java.util.Random; import javafx.animation.KeyFrame; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import static javafx.application.Application.launch; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.util.Duration; /** * * @author jose */ public class Finch extends Application { //We turn on the inbuilt random generator: static private Random r = new Random(); //Our single symbol notation for notes : //A, _B, B, C #C D _E E F #F G #G A _B B c #c d _e e f #f g #g a _b b //R S T C M D N E F O G P A Q B c m d n e f o g p a q b //All possible notes we use in one letter notation /*static private String SUPER_ALPHABET = "RSTAMBCNDOEFPGQambcndoefpgq";*/ static private String alphabet = "RTCDEOGabcdeo"; static private String durationsAlphabet = "1111222222448"; //============Variables for EarTrainer======= //************************************************ //******** Definition and default initialization //********* of an instantiation of MusiText //************************************************ private MusiText3 n; protected static TextArea myTextArea; protected static FileChooser myChooser; static private File myFile; static private String myFileName = ""; //creates a simple midi player to play the melody static private TunePlayer player = new TunePlayer(); static private boolean print = false; private static String scoreSelectionABC, lyricsSelectionABC; //Initialization String musiText2 = "X:0\n" + "T:Song \n" + "M:4/4\n" + "L:1/4\n" + "Q: 100\n" + "K:C\n" + "dd2d |ded2 |GB3 | " + "BBBA | A3 A | dAB2 |" + " AAAA | B2A A | G4 | " + "Gded- |d edG | B4 | " + "BBA2 | A A3 | BAG2|" + "GGGA-|A2 B2 | A4 | G4"; String Help = "READ ME \n " + "-. This is the TextArea. CLEAR IT before any " + "operation: \n " + " Click on it and Use control + A + X \n" + "-. TO OPEN AN ABC file with a tune: \n" + " File -> Open...\n" + "-. TO SAVE AN ABC tune:\n" + " The suffix of ABC tunes is .abc \n" + " File -> SaveAs...\n" + "-. TO PLAY A VERY SIMPLE ABC TUNE:\n" + " Paste THE ABC tune into the editor window and\n " + " ABCMusic -> ShowAndPlayTune\n" + "-. TO PLAY A PROTEIN SEQUENCE in one letter notation:\n" + " Paste the sequence to the text area and\n" + " FirstTheory -> ProteinToTune\n " + "-. TO PLAY A DNA SEQUENCE:\n" + " Paste the sequence to the text area and\n" + " FirstTheory -> DNAToTune\n " + "-. TO TRAIN YOUR EAR WITH PITCH RECOGNIZING: \n" + " EarTrainer -> EarTrainer: \n" + " Keep in mind that learning means an \n" + " evolutionary process in the brain to build and \n" + " program neural networks to respond adequately \n" + " against complexity." + "-. TO KEEP A RECORD of your performance \n" + " in Ear training: \n" + " a. Open a new account with your name and \n" + " use the suffix .ear and \n" + " In the emerging window choose: New account \n" + " b. Reopen your account for every session:\n" + " In the emerging window choose: \n " + " Continue training.\n " + " c. To end your session and update your account:\n" + " In the emerging window choose: \n " + " Save and end session. \n " + " d. As you progress, you rise up from low \n " + " complexity, only two notes, to higher complexity\n " + " up to 27 notes. \n " + " Gain points and go up. \n" + " For a given level of complexity you have \n " + " 8 degrees of expertise, from 0 to 7. \n " + " More expertise means less \n " + " tolerance, less opportunities to commit errors. \n" + " Concentration is determinant. \n " + " e. If you need more training, \n" + " you have two options: \n" + " to return to a lower level of complexity or \n" + " to augment tenacity of the test.\n" + " You can generate random tunes \n" + " that can be shown and played. \n" + " Use them to learn to read sheets music.\n" + " Try evolution as a musc composer in the menu\n " + " Evolution.\n" + "-. Use control + A to SELECT ALL,\n " + "-. Use control + V to PASTE the content\n " + " of the clipboard.\n " + "-. TO STOP THE PLAYER: Panic -> Panic \n" + "-. ACCELERATORS: \n" + " Alt + the underscored letter of the menu." + "\n" + "To play a protein sequence: \n" + "translate it to single letter notation \n" + "and paste it to the textArea.\n" + "The 20 naturally occuring amino acids:\n" + "\n" + "Alanine Ala A\n" + "Cysteine Cys C\n" + "Aspartic AciD Asp D\n" + "Glutamic Acid Glu E\n" + "Phenylalanine Phe F\n" + "Glycine Gly G\n" + "Histidine His H\n" + "Isoleucine Ile I\n" + "Lysine Lys K\n" + "Leucine Leu L\n" + "Methionine Met M\n" + "AsparagiNe Asn N\n" + "Proline Pro P\n" + "Glutamine Gln Q\n" + "ARginine Arg R\n" + "Serine Ser S\n" + "Threonine Thr T\n" + "Valine Val V\n" + "Tryptophan Trp W\n" + "TYrosine Tyr Y" + "\n" + "To permutate a tune" + "\nClear the textArea, " + "\npaste an abc tune," + "\nand apply the permutator."; static private boolean equalDuration; private static boolean FileOpen = false; private static Stage firstStage; private static Stage secondStage; private static String header68String = "X:0\n" + "T:Song 6/8\n" + "M:6/8\n" + "L:1/8\n" + "Q:150\n" + "K:C\n"; private static String header44String = "X:0\n" + "T:Song 4/4\n" + "M:4/4\n" + "L:1/8\n" + "Q:150\n" + "K:C\n"; public Finch() { this.n = new Finch.MusiText3(); //firstStage = new Stage(); //secondStage = new Stage(); } @Override public void start(Stage primaryStage) { firstStage = primaryStage; firstStage.setTitle("FINCH: A GUI to enjoy music"); StackPane root = new StackPane(); Scene scene = new Scene(root, 600, 650, true); firstStage.setScene(scene); MenuBar menuBar = createMenuBar(); VBox vBox = new VBox(); vBox.setMaxHeight(1100); root.getChildren().add(vBox); //Text area = editing window myTextArea = new TextArea(); myTextArea.setMinSize(600, 620); myTextArea.appendText(Help); vBox.getChildren().addAll(menuBar, myTextArea); secondStage = new Stage(); secondStage.initStyle(StageStyle.UTILITY); secondStage.setTitle("Listen to the sound and click " + " the corresponding note"); secondStage.setX(firstStage.getX()); secondStage.setY(firstStage.getY() + firstStage.getHeight()); secondStage.initOwner(firstStage); //secondStage.initStyle(StageStyle.UTILITY); Platform.setImplicitExit(true); firstStage.setOnCloseRequest(event -> { System.out.println("Stage is closing"); Platform.exit(); System.exit(0); }); firstStage.show(); secondStage.initOwner(firstStage); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } //============================ //============MENU BAR======== //============================ //The menu bar and listeners protected MenuBar createMenuBar() { final MenuBar menuBar = new MenuBar(); //File menu Menu mFile = new Menu("File"); mFile.setOnAction((event) -> { myTextArea.setText(""); }); myChooser = new FileChooser(); myChooser.setInitialDirectory(new File(".")); MenuItem open = new MenuItem("Open"); open.setOnAction((event) -> { try { readFileIntoTextArea(); } catch (IOException ex) { Logger.getLogger(Finch.class.getName()) .log(Level.SEVERE, null, ex); } }); mFile.getItems().add(open); MenuItem save = new MenuItem("SaveAs"); save.setOnAction((event) -> { saveTextAreaToFile(); }); mFile.getItems().add(save); MenuItem exit = new MenuItem("Exit"); exit.setOnAction((event) -> { System.exit(0); }); mFile.getItems().add(exit); menuBar.getMenus().add(mFile); //===================== //TextArea menu Menu textAreaMenu = new Menu("TextArea"); menuBar.getMenus().add(textAreaMenu); MenuItem clearTextArea = new MenuItem("ClearTextArea"); clearTextArea.setOnAction((event) -> { myTextArea.setText(""); }); textAreaMenu.getItems().add(clearTextArea); MenuItem header44 = new MenuItem("Header 4/4"); header44.setOnAction((event) -> { myTextArea.setText(header44String); }); textAreaMenu.getItems().add(header44); MenuItem header68 = new MenuItem("Header 6/8"); header68.setOnAction((event) -> { myTextArea.setText(header68String); }); textAreaMenu.getItems().add(header68); MenuItem showHelp = new MenuItem("showHelp"); showHelp.setOnAction((event) -> { myTextArea.setText(""); myTextArea.appendText(Help); }); textAreaMenu.getItems().add(showHelp); MenuItem printTextArea = new MenuItem("PrintTextArea"); printTextArea.setOnAction((event) -> { String ss = myTextArea.getText(); System.out.println(ss); }); textAreaMenu.getItems().add(printTextArea); //===================== //EarTrainer menu Menu earTrainerMenu = new Menu("EarTrainer"); //mABCmusic.setMnemonic('a'); menuBar.getMenus().add(earTrainerMenu); //Pitch recognizing MenuItem EarTrainer = new MenuItem("EarTrainer"); EarTrainer.setOnAction((event) -> { //Instantiation of application EarTrainer p = new EarTrainer(); //Rest before the first question int lag = 1; p.poseQuestion(lag); }); earTrainerMenu.getItems().add(EarTrainer); //===================== //ABCmusic menu Menu mABCmusic = new Menu("ABCmusic"); //mABCmusic.setMnemonic('a'); menuBar.getMenus().add(mABCmusic); MenuItem playTune = new MenuItem("PlayMyTune"); playTune.setOnAction((event) -> { String ss = myTextArea.getText(); System.out.println(ss); //Get header(headerABC), score (ScoreABC)and lyrics getComponentsABC(ss); Tune tune = n.ABCmusiTextToTune(headerABC + "\n" + scoreABC); n.playTune(tune); }); mABCmusic.getItems().add(playTune); MenuItem playAndShowMyTune = new MenuItem("PlayAndShowMyTune"); playAndShowMyTune.setOnAction((event) -> { String ss = myTextArea.getText(); System.out.println(ss); //Get header(headerABC), score (ScoreABC)and lyrics getComponentsABC(ss); Tune tune = n.ABCmusiTextToTune(headerABC + "\n" + scoreABC); n.DrawTune(tune); n.playTune(tune); }); mABCmusic.getItems().add(playAndShowMyTune); MenuItem playSelection = new MenuItem("PlaySelection"); playSelection.setOnAction((event) -> { String ss = myTextArea.getText(); System.out.println(ss); //Get header(headerABC), score (ScoreABC)and lyrics getComponentsABC(ss); String selection = myTextArea.getSelectedText(); decomposeSelectionTuneABC(selection); //scoreSelectionABC = headerABC + "\n" + scoreSelectionABC; scoreSelectionABC = headerABC + "\n" + scoreSelectionABC; System.out.println("scoreSelectionABC = \n" + scoreSelectionABC); Tune selectionABC = ABCStringToTune(scoreSelectionABC); n.playTune(selectionABC); }); mABCmusic.getItems().add(playSelection); MenuItem playAndShowSelection = new MenuItem("PlayAndShowSelection"); playAndShowSelection.setOnAction((event) -> { String ss = myTextArea.getText(); System.out.println(ss); //Get header(headerABC), score (ScoreABC)and lyrics getComponentsABC(ss); String selection = myTextArea.getSelectedText(); decomposeSelectionTuneABC(selection); //scoreSelectionABC = headerABC + "\n" + scoreSelectionABC; scoreSelectionABC = headerABC + "\n" + scoreSelectionABC; System.out.println("scoreSelectionABC = \n" + scoreSelectionABC); Tune selectionABC = ABCStringToTune(scoreSelectionABC); n.DrawTune(selectionABC); n.playTune(selectionABC); String text = myTextArea.getText(); System.out.println("Complete text = \n" + text); }); mABCmusic.getItems().add(playAndShowSelection); MenuItem ShowAndPlayExample = new MenuItem("ShowAndPlayExample"); ShowAndPlayExample.setOnAction((event) -> { myTextArea.setText(musiText2); String ss = myTextArea.getText(); System.out.println(ss); //Get header(headerABC), score (ScoreABC)and lyrics getComponentsABC(ss); Tune tune = n.ABCmusiTextToTune(headerABC + "\n" + scoreABC); n.DrawTune(tune); n.playTune(tune); }); mABCmusic.getItems().add(ShowAndPlayExample); MenuItem ShowAndPlayRandomNotes = new MenuItem("ShowAndPlayRandomNotes"); ShowAndPlayRandomNotes.setOnAction((event) -> { equalDuration = false; try { String musiText = n.mainRandomMusiText(equalDuration, 70); myTextArea.setText(musiText); Tune tune; tune = n.ABCmusiTextToTune(musiText); n.DrawTune(tune); n.playTune(tune); } catch (IOException e1) { } }); mABCmusic.getItems().add(ShowAndPlayRandomNotes); MenuItem howToPlayMyTune = new MenuItem("HowToPlayMyTune"); howToPlayMyTune.setOnAction((event) -> { showInformation("To play a tune", "Clear the textArea, and" + "\npaste your complete abc tune into it. " + "\nThen: Menu -> ABCmusic -> PLayMyTune."); }); mABCmusic.getItems().add(howToPlayMyTune); MenuItem howToPlaySelection = new MenuItem("HowToPlaySelection"); howToPlaySelection.setOnAction((event) -> { showInformation(" To play a selection", " Paste a complete tune to textArea, and " + "\n select the portion to play." + "\nThen: Menu -> ABCmusic -> PLaySelection."); }); mABCmusic.getItems().add(howToPlaySelection); MenuItem whereToGetTunes = new MenuItem("WhereToGetTunes"); whereToGetTunes.setOnAction((event) -> { showInformation(" Tunes in abc notation can be gotten from", "http://abcnotation.com/" + "\nTunes begin with X:" + "\nCopy the abc text to clipboard and paste it into" + "\nthe cleared textArea." + "\nDelete lines with web links -beginning with F:" + "\nand go to the menu ABCMusic -> PlayAndShowMyTune."); }); mABCmusic.getItems().add(whereToGetTunes); //========================= //ShowPLay menu Menu mFirstTheory = new Menu("FirstTheory"); //mFirstTheory.setMnemonic('d'); menuBar.getMenus().add(mFirstTheory); //============= //NotesEqualDuration menu MenuItem NotesEqualDuration = new MenuItem("NotesEqualDuration"); NotesEqualDuration.setOnAction((event) -> { equalDuration = true; try { myTextArea.setText(""); String s = n.mainRandomMusic(equalDuration, 70); myTextArea.setText(s); } catch (IOException e1) { } }); mFirstTheory.getItems().add(NotesEqualDuration); //============= //NotesEqualDuration menu MenuItem NotesUnequalDuration = new MenuItem("NotesUnequalDuration"); NotesUnequalDuration.setOnAction((event) -> { equalDuration = false; try { myTextArea.setText(""); String s = n.mainRandomMusic(equalDuration, 70); myTextArea.setText(s); } catch (IOException e1) { } }); mFirstTheory.getItems().add(NotesUnequalDuration); //========================= //ProteinToTune menu MenuItem ProteinToTune = new MenuItem("ProteinToTune"); ProteinToTune.setOnAction((event) -> { String protein = myTextArea.getText(); try { showInformation("To show and play a protein\n" + "as an ABC tune", "It must be pasted to the cleared textArea." + "See the example."); n.proteinPLayer(protein); } catch (IOException e1) { } }); mFirstTheory.getItems().add(ProteinToTune); //========================= //ProteinToTune menu MenuItem ProteinToTuneExample = new MenuItem("ProteinToTuneExample"); ProteinToTuneExample.setOnAction((event) -> { String protein = n.proteinSequence(); myTextArea.setText(protein); protein = myTextArea.getText(); try { n.proteinPLayer(protein); } catch (IOException e1) { } }); mFirstTheory.getItems().add(ProteinToTuneExample); //========================= //DNAToTune menu MenuItem DNAToTune = new MenuItem("DNAToTune"); DNAToTune.setOnAction((event) -> { String dna = myTextArea.getText(); try { showInformation("To show and play " + "a DNA sequence\n" + "as an ABC tune", "It must be pasted to the cleared textArea." + "See the example."); n.DNAPLayer(dna); } catch (IOException e1) { } }); mFirstTheory.getItems().add(DNAToTune); //========================= //ProteinToTune menu MenuItem DNAToTuneExample = new MenuItem("DNAToTuneExample"); DNAToTuneExample.setOnAction((event) -> { String dna = n.dnaSequence(); myTextArea.setText(dna); dna = myTextArea.getText(); try { n.DNAPLayer(dna); } catch (IOException e1) { } }); mFirstTheory.getItems().add(DNAToTuneExample); //========================= //Statistical version of the first theory MenuItem Permutator = new MenuItem("Permutator"); Permutator.setOnAction((event) -> { String ss = myTextArea.getText(); System.out.println(ss); Permutator(ss); }); mFirstTheory.getItems().add(Permutator); //==========Evolution as a composer====== Menu mEvolution = new Menu("Evolution"); //mPanic.setMnemonic('p'); menuBar.getMenus().add(mEvolution); MenuItem Evolution = new MenuItem("Evolution"); Evolution.setOnAction((event) -> { EvoMusic5 e = new EvoMusic5(); e.start(firstStage); }); mEvolution.getItems().add(Evolution); //========Panic menu Menu mPanic = new Menu("Panic"); //mPanic.setMnemonic('p'); menuBar.getMenus().add(mPanic); MenuItem Panic = new MenuItem("Panic"); Panic.setOnAction((event) -> { player.stopPlaying(); }); mPanic.getItems().add(Panic); return menuBar; }//End of menu bar construction private static void saveTextAreaToFile() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save TextArea to a new file"); //Name of file with extension " FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.obj)", "*.obj"); fileChooser.getExtensionFilters().add(extFilter); File file = fileChooser.showSaveDialog(firstStage); if (file != null) { try (FileWriter out = new FileWriter(file)) { myTextArea.appendText(out.toString()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } myFile = file; } //A file is read with the FileChoser //Result is drawn into TextArea. private static String readFileIntoTextArea() throws IOException { myTextArea.clear(); FileChooser fileChooser = new FileChooser(); //Name of file with extension " FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt"); fileChooser.getExtensionFilters().add(extFilter); //Files will be kept in a list File file = new FileChooser().showOpenDialog(firstStage); String textOfFile = ""; if (file != null) { textOfFile = readFile(file); myTextArea.appendText(textOfFile); myFile = file; myFileName = file.getName(); System.out.println("File name = " + myFileName); } return textOfFile; } private static String readFile(File file) { StringBuilder stringBuffer = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(file)); String text; while ((text = bufferedReader.readLine()) != null) { //System.out.println("ReadFile.text = " + text); stringBuffer.append(text).append("\n"); } } catch (FileNotFoundException ex) { Logger.getLogger(Finch.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Finch.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ex) { Logger.getLogger(Finch.class.getName()).log(Level.SEVERE, null, ex); } } //System.out.println("ReadFile.Buffer = " + stringBuffer.toString()); return stringBuffer.toString(); } //The selected part of a tune is decomposed // into scoreSelection + lyricsSelection private static void decomposeSelectionTuneABC(String selection) { scoreSelectionABC = ""; lyricsSelectionABC = ""; String lineTune; int l; int nBeginS = 0; int nEndS; String tailSelection = selection; boolean accumulate = true; while (accumulate) { if (tailSelection.contains("\n")) { System.out.println("Tail of selection = \n" + tailSelection); int length = tailSelection.length(); System.out.println("length = " + length); System.out.println("Beginning = " + nBeginS); l = tailSelection.indexOf("\n") + 1; nEndS = l; System.out.println("end = " + nEndS); lineTune = tailSelection.substring(nBeginS, nEndS); tailSelection = tailSelection.substring(nEndS); System.out.println("line of tune: " + lineTune); if (lineTune.contains("w:")) { lyricsSelectionABC = lyricsSelectionABC + lineTune; } else { scoreSelectionABC = scoreSelectionABC + lineTune; } } else { accumulate = false; } }//End of while if (tailSelection.contains("w:")) { lyricsSelectionABC = lyricsSelectionABC + tailSelection; } else { scoreSelectionABC = scoreSelectionABC + tailSelection; } System.out.println("ScoreSelectionABC: \n" + scoreSelectionABC); System.out.println("LyricsSelectionABC: \n" + lyricsSelectionABC); } //An ABC-string is transformed into a tune private static Tune ABCStringToTune(String ss) { Tune tune = new TuneParser().parse(ss); return tune; } //************************************************* //The MusiText class is inserted as an inner class //************************************************* public class MusiText3 { String musiText; //Constructor //This specifies how a musiText is initialized. //Here, it acquires information from a String MusiText3(String a) { this.Codons = "AA-AT-AC-AG-TA-TA-TC-TG-CA-CT-CC-CG-GA-GT-GC-GG-"; this.header68 = "X:0\n" + "T:Song 6/8\n" + "M:6/8\n" + "L:1/8\n" + "K:C\n"; this.header44 = "X:0\n" + "T:Song 4/4\n" + "M:4/4\n" + "L:1/8\n" + "K:C\n"; this.Notes = new String[]{"C", "^C", "D", "_E", "E", "F", "^F", "G", "^G", "A", "_B", "B", "c", "^c", "d", "_e", "e", "f", "^f", "z"}; this.aminoAcids = "ARNDCEQGHILKMFPSTWYVZ"; musiText = a; } //One can initialize it by default MusiText3() { this.Codons = "AA-AT-AC-AG-TA-TA-TC-TG-CA-CT-CC-CG-GA-GT-GC-GG-"; this.header68 = "X:0\n" + "T:Song 6/8\n" + "M:6/8\n" + "L:1/8\n" + "K:C\n"; this.header44 = "X:0\n" + "T:Song 4/4\n" + "M:4/4\n" + "L:1/8\n" + "K:C\n"; this.Notes = new String[]{"C", "^C", "D", "_E", "E", "F", "^F", "G", "^G", "A", "_B", "B", "c", "^c", "d", "_e", "e", "f", "^f", "z"}; this.aminoAcids = "ARNDCEQGHILKMFPSTWYVZ"; musiText = "X:0\n" + "T:The scale \n" + "M:4/4\n" + "K:C\n" + "CDEFGABc4 cBAGF - EDC8"; } //========================== //Randomness is made into a composer String randomNotes(boolean equalDuration, int n) { //Number of notes //Output initialization String stringOfNotes = ""; for (int i = 0; i < n; i++) { //A note is generated: //A random integer less than the //number of chars in the alphabet is thrown int k = r.nextInt(alphabet.length()); //The integer is changed into a note char c = alphabet.charAt(k); //The note is added to the output stringOfNotes = stringOfNotes + c; if (equalDuration); else {//Duration is generated k = r.nextInt(durationsAlphabet.length()); //The integer is changed into a duration c = durationsAlphabet.charAt(k); //The note is added to the output stringOfNotes = stringOfNotes + c; } } return stringOfNotes; } //A string in our alphabet is rewritten in ABC notation //Accidents are prefixes in ABC notation. //Sharp is denoted by ^, flat by _ //Aminoacids: ARNDCEQGHILKMFPSTWYVZ //"C", "^C", "D", "_E", "E", "F", "^F", "G", "^G", "A", "_B", "B", "c", "^c", "d", "_e", "e", "f", "^f", "z"}; private String interpreter(String ss) { ss = ss.replaceAll("R", "A,"); ss = ss.replaceAll("S", "_B,"); ss = ss.replaceAll("T", "B,"); ss = ss.replaceAll("M", "#C"); ss = ss.replaceAll("M", "#c"); ss = ss.replaceAll("N", "_E"); ss = ss.replaceAll("n", "_e"); ss = ss.replaceAll("O", "^F"); ss = ss.replaceAll("o", "^f"); ss = ss.replaceAll("P", "^G"); ss = ss.replaceAll("p", "^g"); ss = ss.replaceAll("Q", "_B"); ss = ss.replaceAll("q", "_b"); return ss; } String mainRandomMusiText(boolean equalDuration, int numberOfNotes) throws IOException { //Initialization String header = "X:0\n" + "T:Song \n" + "M:4/4\n" + "L:1/8\n" + "K:C\n"; String ss = randomNotes(equalDuration, numberOfNotes); ss = interpreter(ss); String musiTextss = header + ss; return musiTextss; } String mainRandomMusic(boolean equalDuration, int numberOfNotes) throws IOException { String musiTextss = mainRandomMusiText(equalDuration, numberOfNotes); Tune tune; tune = ABCmusiTextToTune(musiTextss); DrawTune(tune); playTune(tune); return musiTextss; } //============================ //====== Protein to ABC tune //============================ //Our genetic code: amino acids and //the corresponding durations: //Amino acids in line 1; notes in line 2; //durations for 4/4 in line 3, for 6/8 in line 4. //A virtual amino acid, Z; has been added to let us //concatenate two chains with an ABC rest. //A R N D C E Q G H I L K M F P S T W Y V Z //C ^C D _E E F ^F G ^G A _B B c ^c d ^d _e e f ^f z //1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 4 4 4 8 8 8 // 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 6 6 6 6 private final String aminoAcids; private final String[] Notes; //Durations for 4/4 private final String durationsAlphabet44 = "111112222222222444888"; private final String header44; //Durations for 6/8 private final String durationsAlphabet68 = "111111111333333336666"; private final String header68; //Amino acids in the first position of a codon //are interpreted as notes. //Interpretation is done amino acid per amino acid. private String notesInterpreterProt(char a) { System.out.println("a = " + a); //The index of a is looked at the list of amino acids int i = aminoAcids.indexOf(a); //The corresponding note is looked at the array of notes String ss = Notes[i]; return ss; } //Amino acids in the second position of a codon //are interpreted as durations of notes. //Interpretation is done amino acid per amino acid. //measure = 44 for 4/4; measure = 68 for 6/8; private char durationsInterpreterProt(char a, int measure) { //The index of a is looked at the list of amino acids int i = aminoAcids.indexOf(a); //The corresponding duration is looked //at the list of durations char c; if (measure == 44) { c = durationsAlphabet44.charAt(i); } else { c = durationsAlphabet68.charAt(i); } return c; } //A protein is transformed into a tune. //It is divided in codons with 2 letters, //the first is interpreted as a note, //the second as a duration private String interpreterProt(String s, int measure) { String v = ""; int l = s.length(); for (int i = 0; i < l - 2; i++) { char a = s.charAt(i); String note = notesInterpreterProt(a); //System.out.println("a = " + a); i++; a = s.charAt(i); //System.out.println("a = " + a); char duration = durationsInterpreterProt(a, measure); v = v + note + duration; } return v; } private void proteinPLayer(String protein) throws IOException { protein = protein.replace("\n", ""); String header; //Measure 44 for 4/4, 68 for 6/8 int measure = 44; int l = protein.length(); //if l is odd (not even), the last amino acid is trimmed. if (!(l == 0 % 2)) { l = l - 1; protein = protein.substring(0, l); } System.out.println("Protein = " + protein); String ABCstring = interpreterProt(protein, measure); System.out.println("Protein to ABCstring = " + ABCstring); if (measure == 44) { header = header44; } else { header = header68; } String musiTextabc = header + ABCstring; Tune tune; tune = ABCmusiTextToTune(musiTextabc); DrawTune(tune); playTune(tune); } String proteinSequence() { /* Sequence of protein ">sp|P05067|A4_HUMAN Amyloid beta A4 protein OS=Homo sapiens GN=APP PE=1 SV=3\n" */ String protein = "MLPGLALLLLAAWTARALEVPTDGNAGLLAEPQIAMFCGRLNMHMNVQNGKWDSDPSGTK\n" + "TCIDTKEGILQYCQEVYPELQITNVVEANQPVTIQNWCKRGRKQCKTHPHFVIPYRCLVG\n" + "EFVSDALLVPDKCKFLHQERMDVCETHLHWHTVAKETCSEKSTNLHDYGMLLPCGIDKFR\n" + "GVEFVCCPLAEESDNVDSADAEEDDSDVWWGGADTDYADGSEDKVVEVAEEEEVAEVEEE\n" + "EADDDEDDEDGDEVEEEAEEPYEEATERTTSIATTTTTTTESVEEVVREVCSEQAETGPC\n" + "RAMISRWYFDVTEGKCAPFFYGGCGGNRNNFDTEEYCMAVCGSAMSQSLLKTTQEPLARD\n" + "PVKLPTTAASTPDAVDKYLETPGDENEHAHFQKAKERLEAKHRERMSQVMREWEEAERQA\n" + "KNLPKADKKAVIQHFQEKVESLEQEAANERQQLVETHMARVEAMLNDRRRLALENYITAL\n" + "QAVPPRPRHVFNMLKKYVRAEQKDRQHTLKHFEHVRMVDPKKAAQIRSQVMTHLRVIYER\n" + "MNQSLSLLYNVPAVAEEIQDEVDELLQKEQNYSDDVLANMISEPRISYGNDALMPSLTET\n" + "KTTVELLPVNGEFSLDDLQPWHSFGADSVPANTENEVEPVDARPAADRGLTTRPGSGLTN\n" + "IKTEEISEVKMDAEFRHDSGYEVHHQKLVFFAEDVGSNKGAIIGLMVGGVVIATVIVITL\n" + "VMLKKKQYTSIHHGVVEVDAAVTPEERHLSKMQQNGYENPTYKFFEQMQN"; return protein; } //============================ //====== DNA to ABC tune //============================ //Our genetic code: In the first line we see our 16 codons //with a pair of bases. In the second line we see the //associated notes. In the third the duration for 4/4 //and in the last line the durations for 6/8. //A rest is included as a note. private final String Codons; //Codons are taken by pairs. //The first codon //is interpreted as a note. //Interpretation is done codon per codon. private String notesInterpreterDNA(String cd) { //The index of cd is looked at the list of amino acids cd = cd + "-"; int i = Codons.indexOf(cd); i = i / 3; System.out.println("i = " + i); //The corresponding note is looked at the array of notes String ss = Notes[i]; return ss; } //Codons are taken by pairs. //The second codon //is interpreted as a duration. //Interpretation is done codon per codon. private char durationsInterpreterDNA(String cd, int measure) { //The index of cd is looked at the list of amino acids cd = cd + "-"; int i = Codons.indexOf(cd); i = i / 3; //The corresponding duration is looked //at the list of durations char c; if (measure == 44) { c = durationsAlphabet44.charAt(i); } else { c = durationsAlphabet68.charAt(i); } return c; } //A dna sequence is transformed into a tune. //The sequence is divided in pair of codons //each one with 2 letters, //the first codon is interpreted as a note, //the second as a duration private String interpreterDNA(String s, int measure) { String v = ""; int l = s.length(); System.out.println("l = " + l); for (int i = 0; i < l - 4; i = i + 4) { String cd = s.substring(i, i + 2); System.out.println("cd = " + cd); String note = notesInterpreterDNA(cd); cd = s.substring(i + 2, i + 4); System.out.println("cd = " + cd); char duration = durationsInterpreterDNA(cd, measure); v = v + note + duration; } return v; } private String dnaSequence() { //OTTHUMT00000257844 intron 7:_unprocessed_pseudogene String adn = "GTCCCCTCCAAATGTGTCCTGGACAGCCCTGGGACCATGGGACAGACCTAGCCCAGGAAG" + "CCCATGGGGACCTCGACACCAGGCCCTGCCCAGGCCCATCAGGACTAAGAAGGAGATCAG" + "GAGATACCCCCACTGCAACATGGGCACCTGTATCTGGAAGGAACCAGGGTGGCACCCACC" + "AGCTTCCCCGCAGCCCCAGATACCTTGGAAGATCCCATTCAATGGGGAAGCTGGTCCCAT" + "CAAGGCCACAAGAGAGAGACGTGAGCACGGCATCCCTGCAGCCCCAGACAGCCAGCAGTA" + "TGGACCTGGGGCACAATACCCAGGCCAAGAGTGGCCTGGCCTAGACCCCAGCCCTGGGAA" + "GAGAGGGGTACCAGGGCTGTGGTGGGCTCCCAGCTGCAGTCAGCATGACCATGCAGGGGA" + "CCCTGGCACTGCAGAGCTCTGCATTGTCACAATTCACCTTACAGAACCGGGGAGAGATCT" + "CGAAGCCTTGCAGCCACTGCTGCAGCCACAGCAGGTGCCACCACCACGTGCCTTCCAGCT" + "GCCAGTGCAGGCTCTCCTGACAGCAGGGCACCCTGCAGCCCTCACCTCAGCAGCTCAGAC" + "TCTGAAGGTATCTGTTGTTCATGTTCCCAGTGCTCCCACCAAAGAGAATTACTACAGAGA" + "ATACTCTTGGTCCTGAGGTGGGCAAAACAGCATGCCCTGTGGATGGAGCCGGCTTCTTTC" + "CCAGCCACCATGCTTGCTGGATGGGCCCGCAGAGCAAGTGGCCATGAGACGGGCATGGGG" + "ACGGGAGAGGCTCAGCATCCTGCACATGCCCTTACCAAGGCTCACCAGGCTGACACCACT" + "GCTGAGCGCCTTGTCTGTGGAAAACAGATTCACACCCAACCCCTGGGATGGCACC"; return adn; } private void DNAPLayer(String adn) throws IOException { String header; //Measure 44 for 4/4, 68 for 6/8 int measure = 44; if (measure == 44) { header = header44; } else { header = header68; } //adn is is trimmed to a length multiple of 4 int l = adn.length(); int f = l / 4; int g = f * 4; //l = g; adn = adn.substring(0, g); String ABCstring = interpreterDNA(adn, measure); System.out.println("ABCstring = " + ABCstring); String musiTextabc = header + ABCstring; Tune tune; tune = ABCmusiTextToTune(musiTextabc); DrawTune(tune); playTune(tune); } //===========PITCH RECOGNIZING=============== //===========ABC tools===== //A tune from a file is read into an usable tuneBook TuneBook ABCfileToBookTune(File abcFile) throws FileNotFoundException { //creates a tunebook from the previous file TuneBook book = new TuneBook(abcFile); return book; } //A tune is retrieved from a TuneBook Tune RetrieveTuneFromBook(TuneBook book) { //A book possibly contains various tunes. // Choose one, pick its index (in the X: field) and //assign it to tuneIndex else define //tuneIndex = book.getHighestReferenceNumber(); int tuneIndex = book.getHighestReferenceNumber(); Tune tune = book.getTune(tuneIndex); return tune; } //An indexed tune is retrieved from a TuneBook Tune RetrieveTuneFromBook(TuneBook book, int tuneIndex) { //A book possibly contains various tunes. // Choose one and pick its index (in the X: field) Tune tune = book.getTune(tuneIndex); return tune; } //A musiText is transformed into a tune Tune ABCmusiTextToTune(String musiText) { //From String to Tune Tune tune = new TuneParser().parse(musiText); return tune; } //A tune as Tune is drawn //Try tunes without regulative instructions or lyrics JScoreComponent DrawTune(Tune tune) { //creates a component that draws the melody on a stave JScoreComponent jscore = new JScoreComponent(); jscore.setJustification(true); jscore.setTune(tune); Frame j = new Frame(); j.add(jscore); j.pack(); j.setVisible(true); WindowListener wndCloser = new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { j.dispose(); player.stopPlaying(); } }; j.addWindowListener(wndCloser); return jscore; } //A tune is played void playTune(Tune tune) { //Displays the title of the tune System.out.println("Title = " + tune.getTitles()[0]); // and its key System.out.println("Key = " + tune.getKey().toLitteralNotation()); player.start(); player.play(tune); } }//End of inner class MusiText //======================================= //========PITCH RECOGNIZING============ //==================================== //Program h76 PicthRecognizing5 //A training facility //for pitch recognizing. //We have seven levels of expertise from 0 to 7 and //25 levels of complexity from 2 to 27. //That level is determined by the number of notes //that are in the training set. //A soft increase in complexity enables success //and therefore learning: //one can pass from a very simple test //to the following level of complexity and so on //without killing the application to begin a new one. //One can choose expertise and complexity level at will //else go from start to end as if in one session. static final class EarTrainer extends BorderPane { //This is the set of all notes we use: private static final String[] NOTES = {"A,", "_B,", "B,", "C", "^C", "D", "_E", "E", "F", "^F", "G", "^G", "A", "_B", "B", "c", "^c", "d", "_e", "e", "f", "^f", "g", "^g", "a", "_b", "b", "c'"}; //======================================================= //=============Working set of notes====================== //=============Make changes as desired=================== //======================================================= //To present notes to the student in that natural order //is most possibly not the most efficient way for teaching. //Our proposal is to try to observe the greatest distance //among notes, such as in the following ordered list. //The workingSet for level k takes //the first k elements of this set // (but must be displayed in the natural order): private static final String[] NOTES_WORKING_ORDER = {"C", "c", "c'", "G", "g", "E", "e", "A,", "A", "a", "D", "d", "F", "f", "B,", "B", "b", "^F", "^f", "_B,", "_B", "_b", "^C", "^c", "^G", "^g", "_E", "_e"}; //======================================================= //======================================================= //======================================================= //In consequence, the next vector keeps the order //of appearance of notes in the graded levels of complexity: private static final int NNWS = NOTES_WORKING_ORDER.length; private static final int[] NOTES_ORDER = new int[NNWS]; //For level of complexity k, the working set //takes the first k notes of NOTES_WORKING_ORDER. //But the chosen elements must be presented //in the List in natural order. //All this meshing bookkeeping is difficult. //To achieve this, we MARK the chosen elements //in the set notes to guide ourselves. private static final boolean[] MARK = new boolean[NOTES.length]; //To make a point you need to find the pitch //before tolerance is wasted. //Actual number of gained points private static int gainedPointsThisSeries = 0; private static int lastRun = 0; private static int topThisSession = 0; //Every ABC tune must have a correct header private static final String HEADER = "X:0\n" + "T:Song 4/4\n" + "M:4/4\n" + "L:1/8\n" + "K:C\n"; //The note that must be recognized as a tune private static Tune tuneTest; //The note that must be recognized as a String private static String noteTest; //Number of tries of today //(in the current levels of complexity and expertise) private static int trialsOfThisSession = 0; //trials after the last grade = //new level of expertise or of complexity private static int trialsOfThisSeries = 0; //Counter of good points in this session private static int gainedPointsOfThisSession = 0; private static String oldNote = ""; //The User must declare which degree of expertise //he or she wants to play with: //Expertise: //0 (deaf), 1(beginner), 2(intermediate), //3 (in the right path), 4 (advanced), //5 (very advanced), 6 (quasi-expert) , 7(expert). private static int expertise = 0; private static final int EXPERTISE_LEVELS = 8; //Each test has a complexity level //which is the size of the working set. //Index runs from 0 to 27. private static int levelOfComplexity = 2; //Number of trials granted before failure declaration private int failuresPardoned; private static int tenacity = 4; private int neededPoints; //A rest prior the playing of a tune. private static Integer lag = 8; //Did the User open a file where he or she //keeps his or her records? private static boolean fileOpen = false; //We turn on the inbuilt random generator: private static final Random RDN = new Random(); private static final Button OK = new Button("OK"); private static final Button GRADE = new Button("GRADE"); private final Button GAINED_POINTS_THIS_SERIES_BUTTON; private static final Button PARDONED_FAILURES_BUTTON = new Button(""); private final Button lastRunButton; private final Button topThisSessionButton; private final Button trialsOfThisSessionButton; private final Button efficiencyOfThisSessionButton; private static float efficiency = 0; private static int totalNumberOfTrials = 0; private final Button totalNumberOfTrialsButton; private static final Button REPEAT_BUTTON = new Button("REPEAT QUESTION = click the rightbutton of the mouse"); private static final Button PLAY_NOTES_BUTTON = new Button("Play training notes"); private static final Button SHOW_STATUS_BUTTON = new Button("Show my status"); private static final Button SELECT_TENACITY_BUTTON = new Button("Choose tenacity"); private static final Button SELECT_EXPERTISE_BUTTON = new Button("Choose expertise"); private static final Button SELECT_COMPLEXITY_BUTTON = new Button("Choose complexity"); private static String report = ""; private static final Button NEW_ACCOUNT_BUTTON = new Button("New account"); private static final Button CONTINUE_TRAINING_BUTTON = new Button("Continue training.........."); private static final Button SAVE_AND_CLOSE_BUTTON = new Button("Save and end session. "); private static final ListView TRAINING_NOTES = new ListView<>(); //Matrix to keep the number of trials made to pass from //the given level of complexity to the next private static final int[][] MEMORY = new int[NOTES.length][EXPERTISE_LEVELS]; //Date private static String date; //Is the User keeping a record of his or her performance? private static final boolean MEMORIZING = false; //Constructor public EarTrainer() { this.neededPoints = tenacity * levelOfComplexity; //Number of trials granted before failure declaration this.failuresPardoned = failuresPardoned(expertise); PARDONED_FAILURES_BUTTON.setText("Lives = " + failuresPardoned); this.GAINED_POINTS_THIS_SERIES_BUTTON = new Button("Gained points : " + 0 + "/" + neededPoints); this.lastRunButton = new Button("Points of last run : " + lastRun); this.topThisSessionButton = new Button("Top of this session : " + topThisSession); this.trialsOfThisSessionButton = new Button("Trials of this session : " + trialsOfThisSession); this.efficiencyOfThisSessionButton = new Button("Efficiency of this session : " + gainedPointsOfThisSession + "/" + trialsOfThisSession); this.totalNumberOfTrialsButton = new Button("Total number of trials : " + trialsOfThisSession); OK.setStyle("-fx-font: 22 arial; -fx-base: ghostwhite;"); //#d3d3d3 = lightgrey GRADE.setStyle("-fx-font: 22 arial; -fx-base: #d3d3d3;"); // Use a border pane as the root for scene BorderPane border = new BorderPane(); HBox hbox = addHBox(); border.setTop(hbox); border.setLeft(addVBox()); // Add a stack to the HBox in the top region addStackPane(hbox); // To see only the grid in the center, uncomment // the following statement // comment out the setCenter() call farther down // border.setCenter(addGridPane()); // Choose either a TilePane or FlowPane // for right region and comment out the // one you aren't using border.setRight(addFlowPane()); border.setBottom(addTilePane()); // To see only the grid in the center, //comment out the following statement // If both setCenter() calls are executed, //the anchor pane from the second // call replaces the grid from the first call border.setCenter(addAnchorPane(addGridPane())); Scene scene = new Scene(border); secondStage.setScene(scene); Platform.setImplicitExit(true); secondStage.show(); //Rest before the first question lag = 1; //Expertise: //0 (deaf), 1(beginner), 2(intermediate), //3 (in the right path), 4 (advanced), //5 (very advanced), 6 (semi-expert), 7(expert). expertise = EXPERTISE_LEVELS - 2; //Number of points that are needed to graduate //from the second initial level of complexity neededPoints = tenacity * levelOfComplexity; getNotesOrder(); //The memory matrix is zeroed initializeMemory(); player.start(); if (((expertise <= EXPERTISE_LEVELS) & (levelOfComplexity < NOTES.length)) & (levelOfComplexity >= 2)) { //There is no MARK ed note at the beginning for (int i = 0; i < NOTES.length; i++) { MARK[i] = false; } initializeModel(levelOfComplexity); //Begin training poseQuestion(lag); makeTest(); } else { //System.out.println("Test over"); showInformation("Triumph", "Test over"); } secondStage.setOnCloseRequest(event -> { System.out.println("Stage is closing"); try { saveAndClose(); } catch (IOException ex) { Logger.getLogger(Finch.class.getName()).log(Level.SEVERE, null, ex); } secondStage.close(); }); TRAINING_NOTES.getSelectionModel().selectedItemProperty().addListener((ObservableValue ov, String oldValue, String newValue) -> { TRAINING_NOTES.getSelectionModel().select(ov.getValue()); }); }//End of constructor of EarTrainer6 //================================= /* * Creates an HBox with the Help button for the top region */ private HBox addHBox() { HBox hbox = new HBox(); hbox.setPadding(new Insets(15, 12, 15, 12)); hbox.setSpacing(10); // Gap between nodes //#336699 = blue hbox.setStyle("-fx-background-color: #336699;"); Button buttonHelp = new Button("Help"); buttonHelp.setPrefSize(100, 20); buttonHelp.setOnAction( (event) -> { showInformation("Guidelines", "1.This is a facility to train your ear. \n" + "To just play: over the pane with notes C c...\n" + "rightlick to listen to a note.\n" + "Identify it and click the corresponding symbol.\n" + "To go into a formal plan of training: \n" + "Open an account (->New account), play, \n" + "save and exit->Save and end session.\n" + "To return to a new session: ->Continue training.\n\n" + "2.There are various levels of complexity \n" + "that are given by the number of training notes.\n" + "The level of expertise determines the number of\n" + "tolerated errors without getting chastised.\n" + "The tenacity also determines \n" + "the level of expertise according to: \n" + "neededPoints = tenacity x levelOfComplexity.\n" + "Needed points to pass to the next level \n" + "is the denominator of ->Gained points. \n\n" + "3.To prevent tendinitis:continuously \n" + "rotate clicking fingers and \n" + "also change the clicking hand sporadically." ); } ); Button buttonShowMyHistory = new Button("My history"); buttonShowMyHistory.setPrefSize(100, 20); buttonShowMyHistory.setOnAction( (event) -> { memoryToTextArea(); } ); Button buttonShowDictionary = new Button("Dictionary"); buttonShowDictionary.setPrefSize(100, 20); buttonShowDictionary.setOnAction( (event) -> { showInformation("We use abc notation (http://abcnotation.com/). \n " + "The equivalence to latin notation is shown:", "A, (LA3) " + "_B, (SIb3) " + "B, (SI3) " + "C (DO4) " + "^C (DO#4) " + "\n" + "D (RE4) " + "_E (MIb4) " + "E (MI4) " + "F (FA4) " + "^F (FA#4) " + "\n" + "G (SOL4) " + "^G (SOL#4) " + "A (LA4) " + "_B (SIb4) " + "B (SI4) " + "\n" + "c (DO5) " + "^c (DO#5) " + "d (RE5) " + "_e (MIb5) " + "e (MI5) " + "\n" + "f (FA5) " + "^f (FA#5) " + "g (SOL5) " + "^g (SOL#5) " + "a (LA5) " + "\n" + "_b (SIb5) " + "b (SI5) " + "c' (DO6)" ); } ); hbox.getChildren() .addAll(buttonHelp, buttonShowMyHistory, buttonShowDictionary); return hbox; } /* * Creates a VBox with a list of links for the left region */ private VBox addVBox() { VBox vBox = new VBox(); vBox.setPadding(new Insets(40));// Set all sides to 10 vBox.setSpacing(8); // Gap between nodes //peachpuff = vBox.setStyle("-fx-background-color: peachpuff;"); Text title = new Text("Training set of notes"); title.setFont(Font.font("Arial", FontWeight.BOLD, 14)); vBox.getChildren().add(title); vBox.setMaxHeight(1000); vBox.getChildren().add(TRAINING_NOTES); VBox.setMargin(TRAINING_NOTES, new Insets(0, 0, 0, 0)); return vBox; } /* * Uses a stack pane to create a help icon and adds it to the right side of an HBox * * @param hb HBox to add the stack to */ private void addStackPane(HBox hb) { StackPane stack = new StackPane(); Rectangle helpIcon = new Rectangle(30.0, 25.0); helpIcon.setFill(new LinearGradient(0, 0, 0, 1, true, CycleMethod.NO_CYCLE, new Stop[]{ //#4977A3 = Blue San Marino new Stop(0, javafx.scene.paint.Color.web("#4977A3")), // #B0C6DA = Blue Spindle new Stop(0.5, javafx.scene.paint.Color.web("#B0C6DA")), //#9CB6CF = Echo Blue new Stop(1, javafx.scene.paint.Color.web("#9CB6CF")),})); //#D0E6FA = Pattens blue helpIcon.setStroke(javafx.scene.paint.Color.web("#D0E6FA")); helpIcon.setArcHeight(3.5); helpIcon.setArcWidth(3.5); Text helpText = new Text("?"); helpText.setFont(Font.font("Verdana", FontWeight.BOLD, 18)); helpText.setFill(javafx.scene.paint.Color.WHITE); // #7080A0 = Ship Cove (gray blue) helpText.setStroke(javafx.scene.paint.Color.web("#7080A0")); stack.setOnMousePressed( (event) -> { showInformation("About", "Finch\n version: May/2016\n" + "Author : Jose \nwww.evoljava.com" ); } ); stack.getChildren().addAll(helpIcon, helpText); stack.setAlignment(Pos.CENTER_RIGHT); // Add offset to right for //question MARK to compensate for RIGHT // alignment of all nodes StackPane .setMargin(helpText, new Insets(0, 10, 0, 0)); hb.getChildren().add(stack); HBox.setHgrow(stack, Priority.ALWAYS); } /* * Creates a grid for the center region with four columns and three rows */ private GridPane addGridPane() { GridPane grid = new GridPane(); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(0, 10, 0, 10)); //Button repeat //The posed question must be repeated REPEAT_BUTTON.setOnAction((event) -> { tuneTest = noteToTune("z1" + noteTest + noteTest + noteTest); playTune(tuneTest); }); //Training notes are played and //playing note is selected. PLAY_NOTES_BUTTON.setOnAction((event) -> { SequentialTransition st = new SequentialTransition(); for (int i = 0; i < TRAINING_NOTES.getItems().size(); i++) { String note = TRAINING_NOTES.getItems().get(i); //create a timeline for playing and selecting notes Timeline timeline = new Timeline(); timeline.setCycleCount(1); timeline.setAutoReverse(false); final int f = i; EventHandler playNote = (EventHandler) (ActionEvent) -> { String m = "" + note + "4"; System.err.println("Now playing : " + note); Tune mTune = noteToTune(m); playTune(mTune); TRAINING_NOTES.getSelectionModel().select(f); }; KeyFrame keyFrame = new KeyFrame(new Duration(1000), playNote); timeline.getKeyFrames().add(keyFrame); st.getChildren().add(timeline); } st.setCycleCount(1); st.setDelay(new Duration(0));//this does not work st.play(); }); //Information is displayed SHOW_STATUS_BUTTON.setOnAction((event) -> { showInformation("This is your status", report(tenacity, expertise, levelOfComplexity)); }); //Test can be short for playing else //longer for better training. Default is 4. SELECT_TENACITY_BUTTON.setOnAction((event) -> { String s1 = getInputText("Tenacity level", "Enter desired level of tenacity, ", "1 (for low training), 1, ... , 7 " + "(for very hard training)"); String s = s1.trim(); //translation from char to number tenacity = s.charAt(0) - 48; //System.out.println("Tenacity = " + tenacity); }); //Experts need less tolerance than beginners SELECT_EXPERTISE_BUTTON.setOnAction((event) -> { String s1 = getInputText("Expertise level", "Enter your level of expertise, ", "0 (deaf),1,2,3,4,5,6,7 (expert)"); String s = s1.trim(); //translation from char to number expertise = s.charAt(0) - 48; //System.out.println("Expertise = " + expertise); if (MEMORIZING) //The memory matrix is updated { updateMemory(expertise, levelOfComplexity, trialsOfThisSession); } //New count gainedPointsThisSeries = 0; }); //The training set has 3 notes at the beginning, //4 at the next level and so on until 27. SELECT_COMPLEXITY_BUTTON.setOnAction((event) -> { String s1 = getInputText("Complexity level", "Enter desired level of complexity, ", " from 2 (least) to " + NOTES.length + "(max)"); String s = s1.trim(); int a1 = s.charAt(0) - 48; levelOfComplexity = a1; if (s.length() > 1) { int b = s.charAt(1) - 48; levelOfComplexity = a1 * 10 + b; } //System.out.println("Complexity = "+ levelOfComplexity); if (MEMORIZING) //The memory matrix is updated { updateMemory(expertise, levelOfComplexity, trialsOfThisSession); } //new count gainedPointsThisSeries = 0; initializeModel(levelOfComplexity); poseQuestion(levelOfComplexity); }); //You are allowed to play but if you are decided to //become an expert, open a new account //to keep a record of your performance. NEW_ACCOUNT_BUTTON.setOnAction((event) -> { showInformation("New account", "Begin a new file " + "where you will keep your account. " + "Use your name plus suffix .ear, say" + " BraveSmith.ear." + "\nNext, choose the note else click on Repeat."); //Date is inquired from the system DateFormat dF = DateFormat. getDateInstance(DateFormat.MEDIUM); //date is transformed into a string date = dF.format(new java.util.Date()); //System.out.println(date); //date is written to TextArea Finch.myTextArea.setText(date); //A new file is initialized with //the date when the User began //this experiment with complexity Finch.saveTextAreaToFile(); //Memory is cleared initializeMemory(); }); //Future expert reopens his or her account //on each session CONTINUE_TRAINING_BUTTON.setOnAction((event) -> { //TextArea is cleared Finch.myTextArea.setText(""); showInformation("Your account!", "Open the file " + "where you have your account." + "\nElse open a new acount."); String input = ""; try { input = Finch.readFileIntoTextArea(); } catch (IOException ex) { Logger.getLogger(Finch.class.getName()).log(Level.SEVERE, null, ex); } //String is interpreted as information, //mainly as numbers, //and kept in MEMORY[][] ParseReadString("\n" + input); //You have opened a file and it must be saved fileOpen = true; //Communication to main application FileOpen = fileOpen; //Number of trials granted before failure declaration = lives failuresPardoned = failuresPardoned(expertise); PARDONED_FAILURES_BUTTON.setText("Lives = " + failuresPardoned); }); //Memory of performance is saved to file SAVE_AND_CLOSE_BUTTON.setOnAction((event) -> { try { saveAndClose(); } catch (IOException ex) { Logger.getLogger(Finch.class.getName()).log(Level.SEVERE, null, ex); } }); //Buttons are added to rightPanel grid.add(OK, 0, 0); grid.add(GRADE, 0, 1); grid.add(GAINED_POINTS_THIS_SERIES_BUTTON, 0, 2); grid.add(PARDONED_FAILURES_BUTTON, 0, 3); grid.add(lastRunButton, 0, 4); grid.add(topThisSessionButton, 0, 5); grid.add(trialsOfThisSessionButton, 0, 6); grid.add(efficiencyOfThisSessionButton, 0, 7); grid.add(totalNumberOfTrialsButton, 0, 8); grid.add(REPEAT_BUTTON, 0, 9); grid.add(PLAY_NOTES_BUTTON, 0, 10); grid.add(SHOW_STATUS_BUTTON, 0, 11); grid.add(SELECT_TENACITY_BUTTON, 0, 12); grid.add(SELECT_EXPERTISE_BUTTON, 0, 13); grid.add(SELECT_COMPLEXITY_BUTTON, 0, 14); grid.add(NEW_ACCOUNT_BUTTON, 0, 15); grid.add(CONTINUE_TRAINING_BUTTON, 0, 16); grid.add(SAVE_AND_CLOSE_BUTTON, 0, 17); grid.setGridLinesVisible(true); return grid; } /* * Creates a horizontal flow pane with eight icons in four rows */ private FlowPane addFlowPane() { FlowPane flow = new FlowPane(); flow.setPadding(new Insets(5, 0, 5, 0)); flow.setVgap(4); flow.setHgap(4); // preferred width allows for two columns flow.setPrefWrapLength(170); // lavenderblush = light pink flow.setStyle("-fx-background-color: lavenderblush;"); ImageView pages[] = new ImageView[8]; /* for (int i=0; i<8; i++) { pages[i] = new ImageView( new Image(LayoutSample .class.getResourceAsStream( "graphics/chart_"+(i+1)+".png"))); flow.getChildren().add(pages[i]); }*/ return flow; } /* * Creates a horizontal (default) tile pane with eight icons in four rows */ private TilePane addTilePane() { TilePane tile = new TilePane(); // #fffacd = lemonchiffon (light yellow tile.setStyle("-fx-background-color: #fffacd;"); tile.setPadding(new Insets(5, 0, 5, 0)); tile.setVgap(4); tile.setHgap(4); tile.setPrefColumns(2); /* ImageView pages[] = new ImageView[8]; for (int i=0; i<8; i++) { pages[i] = new ImageView( new Image(LayoutSample .class.getResourceAsStream( "graphics/chart_"+(i+1)+".png"))); tile.getChildren().add(pages[i]); } */ return tile; } /* * Creates an anchor pane using the provided grid and an HBox with buttons * * @param grid Grid to anchor to the top of the anchor pane */ private AnchorPane addAnchorPane(GridPane grid) { AnchorPane anchorpane = new AnchorPane(); anchorpane.getChildren().addAll(grid); AnchorPane.setTopAnchor(grid, 10.0); return anchorpane; } //================================ static void saveAndClose() throws IOException { if (fileOpen) { saveMemory(); makeBackup(); showInformation("Your session has been saved!", "A backup was " + "also made."); System.exit(0); fileOpen = false; } } //The list of notes in NotesWorkingSet is read //and its order in notes[] is found private void getNotesOrder() { int n = NOTES_WORKING_ORDER.length; int m = NOTES.length; for (int i = 0; i < n; i++) { String thisNote = NOTES_WORKING_ORDER[i]; int index = 0; for (int j = 0; j < m; j++) { String thatNote = NOTES[j]; if (thisNote.equals(thatNote)) { index = j; } } NOTES_ORDER[i] = index; //System.out.println( index ); } } //Memory is drawn into TextArea. //TextArea is saved to file private static void saveMemory() throws IOException { Finch.myTextArea.setText(""); updateMemory(expertise, levelOfComplexity, totalNumberOfTrials); memoryToTextArea(); try (BufferedWriter out = new BufferedWriter(new FileWriter(myFile))) { out.write(Finch.myTextArea.getText()); } catch (IOException ex) { } } //Backup is saved to disk private static void makeBackup() { final File myBackUp = new File(myFile.getAbsolutePath() + "backup"); try (BufferedWriter out = new BufferedWriter(new FileWriter(myBackUp))) { out.write(myTextArea.getText()); } catch (IOException ex) { } } //String s that encodes for a number is decoded into number private static int stringToNumber(String s) { int k = s.length(); int number = 0; for (int j = 0; j < k; j++) { char c = s.charAt(j); int l = Character.getNumericValue(c); int q = j + 1; int number1 = (int) (l * Math.pow(10, k - q)); number = number + number1; } return number; } //The string captured from the file //is interpreted as information private void ParseReadString(String input) { System.out.println("\nInput string = " + input); //Input is divided in lines, which are separated by \n String[] tokens = input.split("\n"); int nTokens = tokens.length; System.out.println("Number of tokens = " + nTokens); System.out.println("TOKENS"); for (String t : tokens) { System.out.println(t); } //Each line is deciphered according to //the saved pattern ( a shift of one is needed) date = tokens[1]; tenacity = stringToNumber(tokens[2].trim()); expertise = stringToNumber(tokens[3].trim()); levelOfComplexity = stringToNumber(tokens[4].trim()); neededPoints = tenacity * levelOfComplexity; GAINED_POINTS_THIS_SERIES_BUTTON.setText( "Gained points = " + 0 + "/" + neededPoints); for (int i = 0; i < nTokens; i++) { System.out.println("Token " + i + " " + tokens[i]); } for (int i = 5; i < nTokens; i++) { //String[] tokens2 = tokens[i].split(" "); String[] tokens2 = tokens[i].split("\t"); System.out.println( "NsubTokens for " + i + " = " + tokens2.length); System.out.println(tokens2[0]); for (int j = 1; j < 9; j++) { MEMORY[i - 5][j - 1] = stringToNumber(tokens2[j].trim()); } } System.out.println("Memory numeric"); for (int i = 0; i < NOTES.length; i++) { System.out.printf("%n %10d %10d %10d %10d %10d %10d" + " %10d %10d %10d ", i, MEMORY[i][0], MEMORY[i][1], MEMORY[i][2], MEMORY[i][3], MEMORY[i][4], MEMORY[i][5], MEMORY[i][6], MEMORY[i][7]); } int i = levelOfComplexity; int j = expertise; totalNumberOfTrials = MEMORY[i][j]; totalNumberOfTrialsButton .setText("Total number of trials : " + totalNumberOfTrials); initializeModel(levelOfComplexity); report(tenacity, expertise, levelOfComplexity); } //Memory matrix is zeroed private void initializeMemory() { for (int i = 0; i < NOTES.length; i++) { for (int j = 0; j < 5; j++) { MEMORY[i][j] = 0; } } } //The trials of the session are //added to the Memory matrix. private static void updateMemory(int expertise, int levelOfComplexity, int totalNumberOfTrials) { int i = levelOfComplexity; int j = expertise; MEMORY[i][j] = totalNumberOfTrials; //Correction in case of forgiveness //MEMORY[7][7] = 10401; } //The memory is written to //the console and the text area. private static void memoryToTextArea() { System.out.println("\nDATA SAVED (without the first column): \n"); //memory is displayed on the console System.out.println("Beginning date = " + date); System.out.printf("Tenacity = %3d " + "Expertise = %3d " + "level of complexity = %3d", tenacity, expertise, levelOfComplexity); System.out.printf("\nMemory matrix: number of trials \n" + "needed to pass from a given level of complexity \n" + " to the next. Seven levels of expertise in columns, \n" + "28 levels of complexity in rows. \n"); for (int i = 0; i < NOTES.length; i++) { System.out.printf("%n %10d %10d %10d %10d " + "%10d %10d %10d %10d %10d ", i, MEMORY[i][0], MEMORY[i][1], MEMORY[i][2], MEMORY[i][3], MEMORY[i][4], MEMORY[i][5], MEMORY[i][6], MEMORY[i][7]); } //memory is written to a string String sMemory = "" + date + "\n"; sMemory = sMemory + tenacity + "\n" + expertise + "\n" + levelOfComplexity + "\n"; for (int i = 0; i < NOTES.length; i++) { for (int j = 0; j < EXPERTISE_LEVELS; j++) { /*Integer k = memory[i][j]; String s = k.toString(); */ sMemory = sMemory + "\t" + MEMORY[i][j]; } sMemory = sMemory + "\n"; } //memory is written to the text area Finch.myTextArea.setText(sMemory); } //creates a simple midi player to play the melody private final TunePlayer player = new TunePlayer(); //The musiText is transformed into a tune, //an ABC4J musical object private Tune ABCmusiTextToTune(String musiText) { Tune tune = new TuneParser().parse(musiText); return tune; } //A tune is played private void playTune(Tune tune) { player.play(tune); } //The note is converted into an ABC tune private Tune noteToTune(String note) { String musiText = HEADER + note; Tune tune = ABCmusiTextToTune(musiText); return tune; } //The number of granted trials before failure declaration //depends on expertise and the complexity level private int failuresPardoned(int expertise) { int l; l = EXPERTISE_LEVELS - expertise; return l; } //A complexity level defines each working set //of notes to be recognized. //The starting set has only two notes private void initializeModel() { //The first two elements of NOTES_WORKING_ORDER are MARK ed MARK[NOTES_ORDER[0]] = true; MARK[NOTES_ORDER[1]] = true; TRAINING_NOTES.getItems().add(0, NOTES[NOTES_ORDER[0]]); TRAINING_NOTES.getItems().add(1, NOTES[NOTES_ORDER[1]]); } //A complexity level defines each working set //of notes to be recognized. //The starting set has only two notes private void initializeModel(int levelOfComplexity) { reinitializeModel(); //The corresponding elements of NOTES_WORKING_ORDER are MARK ed //and inserted into the model for (int i = 2; i < levelOfComplexity; i++) { insertNote(i); } } private String report(int tenacity, int expertise, int levelOfComplexity) { /*System.out.println("Position " + "of new note = " + NOTES_ORDER[levelOfComplexity-1] ); System.out.println("New noteTest " + notes[NOTES_ORDER[ levelOfComplexity-1]] );*/ neededPoints = tenacity * levelOfComplexity; failuresPardoned = failuresPardoned(expertise); report = "Tenacity = " + tenacity + "\nExpertise level = " + expertise + "\nLevel of complexity" + "\n=Number of notes under Test = " + levelOfComplexity + "\nYou gain a point if you find " + "\nthe answer before " + failuresPardoned + " trials." + "\nNeeded number of points" + "\nto pass to the next level = " + neededPoints; //System.out.println(report); return report; } //Old information is erased and //a new start is set up private void reinitializeModel() { //System.out.println("\nReinitialization"); TRAINING_NOTES.getItems().clear(); for (int i = 0; i < NOTES.length; i++) { MARK[i] = false; } initializeModel(); lag = 8; } private void insertNote(int k) { //A new note must be accommodated in the right order //Counter of notes less than the new one int counter = 0; //Position in notes[] of the new note int n = NOTES_ORDER[k]; //To find the place of insertion, //all active notes less than the new one are counted for (int i = 0; i < n; i++) { if (MARK[i]) { counter++; } } //The new note is inserted in the TRAINING_NOTES //after all notes less than it. TRAINING_NOTES.getItems().add(counter, NOTES[n]); //The added note is MARK ed MARK[n] = true; } //Outputs a random note from the chosen alphabet private String randomNote() { String newNote; int l = TRAINING_NOTES.getItems().size(); //A random integer less than the //number of allowed notes is thrown int i = RDN.nextInt(l); newNote = TRAINING_NOTES.getItems().get(i); //the new challenge must be different than the prior one //because of selected index if (newNote.contentEquals(oldNote)) { int j = (i + 1) % l; newNote = TRAINING_NOTES.getItems().get(j); } oldNote = newNote; return newNote; } //A random note to be recognized is played void poseQuestion(Integer lag) { String s = lag.toString(); noteTest = randomNote(); /* System.out.println("Random noteTest = " + noteTest); */ tuneTest = noteToTune("z" + s + noteTest + noteTest + noteTest); playTune(tuneTest); //System.out.println("trialsOfThisSeries = " + trialsOfThisSeries); } //One can graduate to the next level of expertise //while conserving the same level of complexity. //Else, one can pass to the next level of complexity, //adding a new note and making expertise = 0. private void updateModel() throws Exception { //The memory matrix is updated updateMemory(expertise, levelOfComplexity, trialsOfThisSession); gainedPointsThisSeries = 0; trialsOfThisSeries = 0; GAINED_POINTS_THIS_SERIES_BUTTON.setText( "Gained points = " + gainedPointsThisSeries + "/" + neededPoints ); //#00ffff = cyan GRADE.setStyle("-fx-font: 22 arial; -fx-base: #00ffff;"); //Lack expertise? Yes= continue if (expertise < EXPERTISE_LEVELS - 1) { System.out.println("NEW LEVEL OF EXPERTISE"); expertise++; showInformation("New level of expertise", "" + expertise); } else //No = Pass to the next level of complexity, add a note { if (levelOfComplexity < NOTES.length - 1) { insertNote(levelOfComplexity); //We have a new level of complexity levelOfComplexity++; // System.out.println("CONGRATULATIONS: " + "you are one level of complexity up!"); showInformation("CONGRATULATIONS: ", "you are one level of complexity up!"); expertise = 0; //Rest, silence lag = 8; report(tenacity, expertise, levelOfComplexity); } } //Number of points that are needed to graduate //from the current level of complexity neededPoints = tenacity * levelOfComplexity; //Number of granted trials before failure declaration failuresPardoned = failuresPardoned(expertise); PARDONED_FAILURES_BUTTON .setText("lives = " + failuresPardoned); } private void makeTest() { TRAINING_NOTES.getSelectionModel().selectedItemProperty().addListener((ObservableValue ov, String oldValue, String newValue) -> { TRAINING_NOTES.setOnMouseReleased((javafx.scene.input.MouseEvent event) -> { if ((expertise <= EXPERTISE_LEVELS) & (levelOfComplexity < NOTES.length)) { MouseButton button = event.getButton(); if (null != button) { switch (button) { case PRIMARY: taskPrimaryButton(newValue); //System.out.println("Primary"); break; case SECONDARY: taskSecondaryButton(); break; case MIDDLE: break; default: break; } } } else { System.out.println("TEST OVER: CONGRATULATIONS"); OK.setStyle("-fx-font: 22 arial; -fx-base: lawngreen;"); REPEAT_BUTTON.setStyle("-fx-font: 22 arial; -fx-base: lawngreen;"); SHOW_STATUS_BUTTON.setStyle("-fx-font: 22 arial; -fx-base: lawngreen;"); /* /* OK.setColor(Color.GREEN); REPEAT_BUTTON.setBackground(Color.GREEN); SHOW_STATUS_BUTTON.setBackground(Color.GREEN); */ showInformation("TEST OVER!", "CONGRATULATIONS!!"); } }); }); }//End of makeTest() private void taskPrimaryButton(String newValue) { trialsOfThisSeries++; trialsOfThisSession++; totalNumberOfTrials++; trialsOfThisSessionButton.setText("Trials of this session : " + trialsOfThisSession); totalNumberOfTrialsButton .setText("Total number of trials = " + totalNumberOfTrials); if (trialsOfThisSeries >= 2) { //#d3d3d3 = lightgrey GRADE.setStyle("-fx-font: 22 arial; -fx-base: #d3d3d3;"); } workOutNewValue(newValue); } private void workOutNewValue(String newValue) { String noteAnswer = newValue; String notesBoth = "z1" + noteTest + "2" + noteAnswer + "2"; Tune tuneBoth = noteToTune(notesBoth); playTune(tuneBoth); /* System.out.println("NoteQuestion = " + noteTest + " noteAnswer = " + noteAnswer); */ //If answer is correct if (noteAnswer.contentEquals(noteTest)) { gainedPointsThisSeries++; gainedPointsOfThisSession++; OK.setText("OK"); OK.setStyle("-fx-font: 22 arial; -fx-base: lawngreen;");//Green //GRADE.setText(""); /* System.out.println( "Your answer "+ noteAnswer + " is RIGHT!"+" Number of trials = " + counterOfTrials + " Gained points = " + gainedPointsThisSeries); */ lag = 8; //Promotion? if (gainedPointsThisSeries >= neededPoints) { try { updateModel(); } catch (Exception e1) { } } poseQuestion(lag); GAINED_POINTS_THIS_SERIES_BUTTON.setText( "Gained points = " + gainedPointsThisSeries + "/" + neededPoints); //A good point after a run of failures //restores previous law if (failuresPardoned == 0) { failuresPardoned = failuresPardoned(expertise); PARDONED_FAILURES_BUTTON .setText("lives = " + failuresPardoned); } } else //if answer is wrong { /* System.out.println("Your answer = " + noteAnswer + " was WRONG!" ); */ lastRun = gainedPointsThisSeries; lastRunButton. setText("Points of last run : " + lastRun); if (lastRun > topThisSession) { topThisSession = lastRun; } topThisSessionButton.setText("Top of this session = " + topThisSession); //If tolerance is exceeded, begin anew if (trialsOfThisSeries > failuresPardoned) { gainedPointsThisSeries = 0; GAINED_POINTS_THIS_SERIES_BUTTON.setText( "Gained points = " + gainedPointsThisSeries + "/" + neededPoints); } //Wrong answers can be pardoned if a limit is not exceeded if (failuresPardoned > 0) { failuresPardoned--; } PARDONED_FAILURES_BUTTON .setText("lives = " + failuresPardoned); OK.setText("OOPS"); OK.setStyle("-fx-font: 22 arial; -fx-base: #ff0000;");//red //GRADE.setText(""); } float gainedPointsOfThisSessionF = gainedPointsOfThisSession; efficiency = gainedPointsOfThisSessionF / trialsOfThisSession; efficiencyOfThisSessionButton.setText("Efficiency of this session : " + gainedPointsOfThisSession + "/" + trialsOfThisSession + " = " + efficiency); } private void taskSecondaryButton() { tuneTest = noteToTune("z1" + noteTest + noteTest + noteTest); playTune(tuneTest); } }//End of EarTrainer public static void showInformation(String title, String message) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.initStyle(StageStyle.UTILITY); alert.setTitle(title); alert.setHeaderText(title); alert.setContentText(message); alert.showAndWait(); } public static String getInputText(String title, String message, String defaultValue) { TextInputDialog dialog = new TextInputDialog(defaultValue); dialog.initStyle(StageStyle.UTILITY); dialog.setTitle("Input"); dialog.setHeaderText(title); dialog.setContentText(message); Optional result = dialog.showAndWait(); if (result.isPresent()) { return result.get(); } else { return null; } } //==========MUSICAL ANALYSIS=============== //A very simple ABC tune is received as input, //it is divided in tokens, component notes, //which are kept in the string vector TokenABC. //To synthesize a new tune with the same distribution //we simply disorder the tune. To that aim, //we permute many pair of tokens in TokenABC. //======================================== private static String[] TokenABC = new String[10000]; private static int nTokensABC = 0; private static String headerABC; private static String bodyABC; private static String scoreABC; private static String lyricsABC; //Delete all spaces private static String deleteAllSpaces(String s) { int length = s.length(); char c; String x = ""; for (int i = 0; i < length; i++) { c = s.charAt(i); if (c == ' '); else { x = x + c; } } //System.out.println("LILY================================== \n" + x); return x; } //An ABC string is divided in tokens, //each one determined by a note //or a bar or slur private static int tokenizeScoreABC(String s) { s = deleteAllSpaces(s); s = s + " "; int length = s.length() - 1; System.out.println("New s V5= \n" + s); System.out.println("Length = " + length); String token = ""; String symbolsABC = "-|"; String accidentsABC = "_^"; String notesABC = "CDEFGABcdefgabz,'"; String durationNumbers = "123456789/"; String starters = "-|_^CDEFGABcdefgabz"; nTokensABC = 0; boolean nextCharIsStarter = false; for (int i = 0; i < length; i++) { char c = s.charAt(i); String sc = "" + c; char nextChar = s.charAt(i + 1); String NextChar = "" + nextChar; if (starters.contains(NextChar)) { nextCharIsStarter = true; } System.out.println("char = " + sc); //If a is a symbol, it is a token if (symbolsABC.contains(sc)) { TokenABC[nTokensABC] = sc; nTokensABC++; //Begin new token token = ""; nextCharIsStarter = false; } else //a is part of a token { //if a is an accident, begin accumulation if (accidentsABC.contains(sc)) { token = sc; nextCharIsStarter = false; } //if a is a note: accumulate if (notesABC.contains(sc)) { //token = token + a; token = token + sc; } //if a is a duration number, accumulate if (durationNumbers.contains(sc)) { //token = token + a; } //if a is followed by a starter: end accumulation //and begin a new token. //Exception: a is an accident if ((nextCharIsStarter) & (!(accidentsABC.contains(sc)))) { TokenABC[nTokensABC] = token; nTokensABC++; token = ""; nextCharIsStarter = false; } //if a is the trailing char, close accumulation if (i == length - 1) { TokenABC[nTokensABC] = token; nTokensABC++; } }//End of else }//EndFor nTokensABC--; if (print) { System.out.println( "Number of tokens = " + " " + nTokensABC); System.out.println("ABC-score tokens"); int nMeasure = 0; for (int i = 0; i < nTokensABC; i++) { System.out.print(i + " " + TokenABC[i]); if (TokenABC[i].contentEquals("|")) { System.out.print(nMeasure); nMeasure++; } System.out.println(); } System.out.println( "Length of input score = " + " " + length); } return nTokensABC; } //A transposition is the interchange of //place between two items. private static void transposition(int nTokensABC) { int m = r.nextInt(nTokensABC); boolean flag = false; //Sites must be different int nn = 0; while (!(flag)) { nn = r.nextInt(nTokensABC); if (!(nn == m)) { flag = true; } } if (print) { System.out.println("Permutation of " + m + " and " + nn); } String aa = TokenABC[m]; String b = TokenABC[nn]; TokenABC[nn] = aa; TokenABC[m] = b; } //Mixer: a sequence of transpositions creates variability. //The output is encoded in a string, a chromosome. private static void mixer(int numberOfTransp, int nTokensABC) { for (int i = 0; i < numberOfTransp; i++) { transposition(nTokensABC); } } //An ABC tune is separated into header + body private static void getComponentsABC(String tuneABC) { int i = tuneABC.indexOf("K:"); System.out.println("K: at = " + i); String h = tuneABC.substring(i); int j = h.indexOf("\n"); System.out.println("eol at = " + j); headerABC = tuneABC.substring(0, i + j); System.out.println("Header = " + headerABC); bodyABC = tuneABC.substring(i + j); System.out.println("bodyABC = " + bodyABC); //Lyrics is separated from score decomposeBodyABC(bodyABC); } //The body of a tune is decomposed into score + lyrics private static void decomposeBodyABC(String body) { scoreABC = ""; lyricsABC = ""; String lineTune; int l; int nBeginS = 0; int nEndS; String tailBody = body; boolean accumulate = true; while (accumulate) { if (tailBody.contains("\n")) { System.out.println("Tail of body = \n" + tailBody); int length = tailBody.length(); System.out.println("length = " + length); System.out.println("Beginning = " + nBeginS); l = tailBody.indexOf("\n") + 1; nEndS = l; System.out.println("end = " + nEndS); lineTune = tailBody.substring(nBeginS, nEndS); tailBody = tailBody.substring(nEndS); System.out.println("line of tune: " + lineTune); if (lineTune.contains("w:")) { lyricsABC = lyricsABC + lineTune; } else { scoreABC = scoreABC + lineTune; } } else { accumulate = false; } }//End of while if (tailBody.contains("w:")) { lyricsABC = lyricsABC + tailBody; } else { scoreABC = scoreABC + tailBody; } System.out.println("Score: \n" + scoreABC); System.out.println("Lyrics: \n" + lyricsABC); } //Output a random letter from the chosen alphabet private static char randomLetter(String alphabet) { int k; //A random integer less than the //number of chars in the alphabet is thrown k = r.nextInt(alphabet.length()); //The integer is changed into a letter of the alphabet char c = alphabet.charAt(k); return c; } private static String assembleTuneABC() { String song = ""; for (int i = 0; i < nTokensABC; i++) { song = song + TokenABC[i] + randomLetter(durationsAlphabet); } return song; } //A one voice ABC tune is received as input. //It is first divided into header plus body, //which is next divided into score + lyrics. //Next, the score is divided in tokens, component notes. //To synthesize a new tune with the same distribution //we simply mix the score. To that aim, //we permute many pair of notes in TokenABC. //Durations are lost in the process so, //new random durations are inserted. private static void Permutator(String tuneABC) { //Get header, score and lyrics getComponentsABC(tuneABC); //Divide the score in tokens nTokensABC = tokenizeScoreABC(scoreABC); //The score is mixed with the help of transpositions. //Number of transpositions int numberOfTransp = 20; mixer(numberOfTransp, nTokensABC); //A new tune is reassembled String song = headerABC + "\n" + assembleTuneABC(); Finch.myTextArea.setText(song); } //========================================================= //=====================EVOLUTION AS A COMPOSER============= //========================================================= //Program H105???? EvoMusic5 //Uses JavaFX. //To learn JavaFX visit //evoljava.com //Lamarckian evolution is made into a composer. //The program provides random musitexts //that are assessed by the User, //that are next subject to mutation and //death according to fitness or score. //Different durations of notes are allowed. //Theoretical guide to composing music: //Notes are pleasant in isolation but when //they go one after another in a tune, //the interval, the number of semitones in //within notes, is what matters. //To facilite mutation, we represent //each note by a single letter. //Say, T represents B. //moreover, we encode musitexts in interval notation. //Example: //T6+33 means: begins with B //(noted T in single letter notation), //with a duration of 6, //+ = prepare to rise pitch, //move 3 semitones up to D //and play it for 3 units of time. //The program outputs ABC musiTexts. //The interval notation we use makes //of recombination a mortiferous machinery. public class EvoMusic5 extends Application { private final Random r = new Random(); //============================= //======Evolutionary module==== //============================= //The player converts the tune into //a midi message that is sent to //hardwared sound synthesizers. //If problems appear, //an input-out exception must be thrown. private final TunePlayer player = new TunePlayer(); //Our one symbol notation. Notes in the first line, //our one letter notation in the second. //A, _B, B, C #C D _E E F #F G #G A _B B c #c d _e e f #f g #g a _b b //R S T C M D N E F O G P A Q B c m d n e f o g p a q b private static final String SUPER_ALPHABET = "RSTCMDNEFOGPAQBcmdnefogpaqb"; //Actual alphabet for work (scale G) private static final String ACTUAL_ALPHABET = "RTCDEOGABcdeo"; //The ABC header private String header; //The working alphabet of durations. private String durationsAlphabet; //Durations for 4/4 private static final String DURATIONS_ALPHABET44 = "1111222222448"; //Header 4/4 private static final String HEADER_44 = "X:0\n" + "T:Song 4/4\n" + "M:4/4\n" + "L:1/8\n" + "K:C\n"; //Durations for 6/8 private static final String DURATIONS_ALPHABET68 = "111111336"; //Header 6/8 private static final String HEADER68 = "X:0\n" + "T:Song 6/8\n" + "M:6/8\n" + "L:1/8\n" + "K:C\n"; /* * Intervals in semitones by rank according to pleasantness (According to the Author): The best: rank zero: 0, 4, 5, 7, 12. Rank one: 9,2 %%Rank two: 8, 3, 6. %%Rank three: 1, 10, 11 */ /* * The 13 intervals in one letter notation: 0 1 2 3 4 5 6 7 8 9 10 11 12 0 1 2 3 4 5 6 7 8 9 a b c */ private static final String INTERVALS = "0123456789abc"; //Rank of the 13 INTERVALS of the scale //{0,3,1,2,0,0,2,0,2,1,3,3,0} private static final String RANK_ZERO = "0457c"; private static final String RANK_ONE = "92"; private static final String RANK_TWO = "836"; private static final String RANK_THREE = "1ab"; //probabilities of appearance depends on rank: private final double prob[] = {0.4, 0.3, 0.2, 0.1}; //The interval can be upwards (1) or downwards (-1); private char signInterval = 1; private int lastNoteIndex; private boolean print = false; private boolean printThis; private boolean drawTune; //==== Variables for evolution====== //The number of individuals must be //less than nMax private static final int N_MAX = 1000; //The population has NUMBER_IND members. private static final int NUMBER_IND = 4; //Ind is a population of individuals private final String Ind[] = new String[N_MAX]; //A helping array to keep a clone of Ind1 private final String IndClone[] = new String[N_MAX]; //The score of each tune is kept here private final double Fitness[] = new double[N_MAX]; //Fitness is used to give a rank to individuals //that define their reproductive possibilities private final int Ordered[] = new int[N_MAX]; private int generation = 0; private TableView table; private TableColumn fitnessCol; private TableColumn chromosomeCol; @Override public void start(Stage primaryStage) { //A measure is chosen //Measure 44 for 4/4, 68 for 6/8 int measure; int j = r.nextInt(2); if (j == 0) { measure = 44; } else { measure = 68; } switch (measure) { case 44: { header = HEADER_44; durationsAlphabet = DURATIONS_ALPHABET44; break; } case 68: { header = HEADER68; durationsAlphabet = DURATIONS_ALPHABET68; break; } } primaryStage.setTitle("Click twice to edit score. " + "After editing, press return to confirm!"); table = new TableView<>(); table.setEditable(true); table.getItems().addAll(createData()); chromosomeCol = new TableColumn<>("Chromosome"); chromosomeCol.setCellValueFactory(cellData -> cellData.getValue().chromosomeProperty()); //chromosomeCol.setCellFactory(col -> new StringEditingCell()); fitnessCol = new TableColumn<>("Score"); fitnessCol.setCellValueFactory(cellData -> cellData.getValue().fitnessProperty()); fitnessCol.setCellFactory(col -> new IntegerEditingCell()); table.getColumns().add(chromosomeCol); table.getColumns().add(fitnessCol); //Listener that plays a musiText table.getSelectionModel().selectedItemProperty() .addListener((obs, oldSelection, newSelection) -> { if (newSelection != null) { System.out.println(newSelection.chromosome + "" + newSelection.fitness); playInd(newSelection.chromosome.getValue()); } }); Button dataDumpButton = new Button("Dump data"); dataDumpButton.setOnAction(e -> table.getItems().stream().map(item -> item.getChromosome() + ":" + item.getFitness()) .forEach(System.out::println)); Button nextGenerationButton = new Button("Next Generation"); nextGenerationButton.setOnAction(e -> { nextGeneration(); }); HBox controls = new HBox(5, dataDumpButton, nextGenerationButton); controls.setPadding(new Insets(10)); controls.setAlignment(Pos.CENTER); primaryStage.setScene(new Scene(new BorderPane(table, null, null, controls, null), 600, 400)); primaryStage.show(); //Music Area player.start(); print = false; printThis = true; drawTune = false; showInformation("Evolution as a composer:", "Select a musiText\n" + "Listen and edit its score." + "\nOnce done, prompt a new generation!"); /* printThis = true; durationsAlphabet = DURATIONS_ALPHABET44; twoPointsMutationInd("T6+33-51+91+83-21-51+01" ); */ } public class StringEditingCell extends TableCell { private TextField textField = new TextField(); public StringEditingCell() { textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> { if (!isNowFocused) { processEdit(); } }); textField.setOnAction(event -> processEdit()); } private void processEdit() { String text = textField.getText(); commitEdit(text); } @Override public void updateItem(String chromosome, boolean empty) { super.updateItem(chromosome, empty); if (empty) { setText(null); setGraphic(null); } else { if (isEditing()) { if (textField != null) { textField.setText(chromosome); } setText(null); setGraphic(textField); } else { setText(chromosome); setGraphic(null); } } } @Override public void startEdit() { super.startEdit(); String chromosome = getItem(); if (chromosome != null) { textField.setText(chromosome); setGraphic(textField); setText(null); } } @Override public void cancelEdit() { super.cancelEdit(); setText(getItem()); setGraphic(null); } private void createTextField() { textField = new TextField(getString()); textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); textField.focusedProperty().addListener((ObservableValue arg0, Boolean arg1, Boolean arg2) -> { if (!arg2) { commitEdit(textField.getText()); } }); } // This seems necessary to persist the edit on loss of focus; not sure why: @Override public void commitEdit(String chromosome) { super.commitEdit(chromosome); ((Item) this.getTableRow().getItem()).setChromosome(chromosome); } private String getString() { return getItem() == null ? "" : getItem(); } }//End of IntegerEditingCell public class IntegerEditingCell extends TableCell { private final TextField textField = new TextField(); private final Pattern intPattern = Pattern.compile("-?\\d+"); public IntegerEditingCell() { textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> { if (!isNowFocused) { processEdit(); } }); textField.setOnAction(event -> processEdit()); } private void processEdit() { String text = textField.getText(); if (intPattern.matcher(text).matches()) { commitEdit(Integer.parseInt(text)); } else { cancelEdit(); } } @Override public void updateItem(Number fitness, boolean empty) { super.updateItem(fitness, empty); if (empty) { setText(null); setGraphic(null); } else if (isEditing()) { setText(null); textField.setText(fitness.toString()); setGraphic(textField); } else { setText(fitness.toString()); setGraphic(null); } } @Override public void startEdit() { super.startEdit(); Number fitness = getItem(); if (fitness != null) { textField.setText(fitness.toString()); setGraphic(textField); setText(null); } } @Override public void cancelEdit() { super.cancelEdit(); setText(getItem().toString()); setGraphic(null); } // This seems necessary to persist the edit on loss of focus; not sure why: @Override public void commitEdit(Number fitness) { super.commitEdit(fitness); ((Item) this.getTableRow().getItem()).setFitness(fitness.intValue()); } }//End of IntegerEditingCell //The population and table are initialized //with random musiTexts private List createData() { List items = new ArrayList<>(); for (int i = 0; i < NUMBER_IND; i++) { String c = randomMTIN(); Ind[i] = c; String m = interpreter(transcription(c)); int l = r.nextInt(6); items.add(new Item(m, l)); Fitness[i] = l; } for (int i = 0; i < NUMBER_IND; i++) { Ordered[i] = 0; } return items; } public class Item { private final StringProperty chromosome = new SimpleStringProperty(); private final IntegerProperty fitness = new SimpleIntegerProperty(); public Item(String chromosome, int fitness) { this.setChromosome(chromosome); this.setFitness(fitness); } public final StringProperty chromosomeProperty() { return this.chromosome; } public final String getChromosome() { return this.chromosomeProperty().get(); } public final void setChromosome(final java.lang.String chromosome) { this.chromosomeProperty().set(chromosome); } public final IntegerProperty fitnessProperty() { return this.fitness; } public final int getFitness() { return this.fitnessProperty().get(); } public final void setFitness(final int fitness) { this.fitnessProperty().set(fitness); } } class EditingCell extends TableCell { private TextField textField; public EditingCell() { } @Override public void startEdit() { if (!isEmpty()) { super.startEdit(); createTextField(); setText(null); setGraphic(textField); textField.selectAll(); } } @Override public void cancelEdit() { super.cancelEdit(); setText((String) getItem()); setGraphic(null); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { if (isEditing()) { if (textField != null) { textField.setText(getString()); } setText(null); setGraphic(textField); } else { setText(getString()); setGraphic(null); } } } private void createTextField() { textField = new TextField(getString()); textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); textField.focusedProperty().addListener((ObservableValue arg0, Boolean arg1, Boolean arg2) -> { if (!arg2) { commitEdit(textField.getText()); } }); } private String getString() { return getItem() == null ? "" : getItem(); } } public void main(String[] args) { launch(args); } //The musiText is transformed into a tune, //an ABC4J musical object private Tune ABCmusiTextToTune(String musiText) { Tune tune = new TuneParser().parse(musiText); return tune; } //A tune is played private void playTune(Tune tune) { player.play(tune); } //A tune as Tune is drawn private void DrawTune(Tune tune) { //creates a component that draws the melody on a stave JScoreComponent jscore = new JScoreComponent(); jscore.setJustification(true); jscore.setTune(tune); JFrame j = new JFrame(); j.add(jscore); j.pack(); j.setVisible(true); } //Output a random letter from the chosen alphabet private char randomLetter(String alphabet) { int k; //A random integer less than the //number of chars in the alphabet is thrown k = r.nextInt(alphabet.length()); //The integer is changed into a letter of the alphabet char c = alphabet.charAt(k); return c; } //Char c is decoded into a number: 'A' is zero. int charToNumber(char c) { String s1 = "" + c; int number = 0; for (int j = 0; j < 26; j++) { char d = (char) (j + 97); String s2 = "" + d; if (s1.equals(s2)) { number = j + 10; } } return number; } //An interval, a number, is proposed //with a probability according to its rank. private int proposeInterval() { int k; Character f = ' '; double w = r.nextDouble(); if (w > 1 - prob[3]) { f = randomLetter(RANK_THREE); } if (w < prob[0] + prob[1] + prob[2]) { f = randomLetter(RANK_TWO); } if (w < prob[0] + prob[1]) { f = randomLetter(RANK_ONE); } if (w < prob[0]) { f = randomLetter(RANK_ZERO); } k = Character.getNumericValue(f); if (k > 9) { k = charToNumber(f); } /* This replaces the following code: if (f == 'a') k = 10; if (f == 'b') k = 11; if (f == 'c') k = 12; if (f == 'd') k = 13; if (f == 'e') k = 14; if (f == 'f') k = 15; if (f == 'g') k = 16; if (f == 'h') k = 17; if (f == 'i') k = 18; if (f == 'j') k = 19; if (f == 'k') k = 20; if (f == 'l') k = 21; if (f == 'm') k = 22; if (f == 'n') k = 23; if (f == 'o') k = 24; */ if (print) { System.out.println("w = " + w + " k = " + k); } return k; } //Output a random interval as string: //the first char is the sign: + upwards, - downwards. //the second is the interval as a one letter number. //The rank of INTERVALS determines its //probability of occurrence. //The output must be compatible with both //SUPER_ALPHABET and ACTUAL_ALPHABET, //this is determined by actualNoteIndex //the index of the last note in the SUPER_ALPHABET private String randomInterval() { if (print) { System.out.println("RandomInterval"); } //Output String randomInterval = ""; String newNote; int newNoteIndex = lastNoteIndex; int direction; boolean generated = false; char intervalOneLetter; while (generated == false) { // a direction is created double p = r.nextDouble(); if (p > 0.5) { signInterval = '+'; direction = 1; } else { signInterval = '-'; direction = -1; } //a random number is generated int n = proposeInterval(); int newTryIndex = newNoteIndex + direction * n; //The corresponding note is checked for compatibility if ((newTryIndex >= 0) & (newTryIndex < SUPER_ALPHABET.length())) { newNote = "" + SUPER_ALPHABET.charAt(newTryIndex ); //Is the new note in the actual alphabet of notes? if (ACTUAL_ALPHABET.contains(newNote)) { generated = true; newNoteIndex = newTryIndex; lastNoteIndex = newNoteIndex; //Interval in one letter notation intervalOneLetter = INTERVALS.charAt(n); randomInterval = "" + signInterval + intervalOneLetter; if (print) { System.out.println("New note = " + newNote); } } } } return randomInterval; } //This method outputs a random musiText in interval notation: //The first note comes as a note in one letter notation //plus a duration //Notes occupy even places in the music of the musiText //while durations go in odd places. //In this way, //randomness is made into a composer. private String randomMTIN() { //MusiText in interval notation String m; //An initialNote begins the musiText String c = "" + randomLetter(ACTUAL_ALPHABET); if (print) { System.out.println("First letter = " + c); } int firstNoteIndex = SUPER_ALPHABET.indexOf(c); //Duration is added m = "" + c + randomLetter(durationsAlphabet); lastNoteIndex = firstNoteIndex; //For the following notes //INTERVALS and durations are next added for (int i = 0; i < 7; i++) { //An interval is generated c = randomInterval(); //The interval is added to the output m = m + c; //A random duration is generated c = "" + randomLetter(durationsAlphabet); //The duration is added to the output m = m + c; } if (print) { System.out.println("Random ind = " + m); } return m; } //Input: a musiText in interval one letter notation //output: a musiText in ABC one letter notation private String transcription(String a) { int m = a.length(); //Output musiText in one letter ABC notation String z; //The first two letters encode the initial note //and duration, these are already in ABC one letter notation z = a.substring(0, 2); int newNoteIndex = SUPER_ALPHABET.indexOf(a.charAt(0)); //The rest of the string encodes INTERVALS and durations. //Our codons have three letters: //one for the direction of the interval, //the other for the interval, //and the third for duration char newNote; int k; for (int i = 2; i < m;) { //The first letter is a sign: //the direction of the interval. char c = a.charAt(i++); //The second letter denotes an interval Character f = a.charAt(i++); //The third note represents a duration char third = a.charAt(i++); if (print) { System.out.println("char 0,1,2 = " + c + " " + f + " " + third); } //Direction is decoded int direction; if (c == '+') { direction = 1; } else { direction = -1; } //Interval is decoded int l = Character.getNumericValue(f); if ((l >= 0) & (l < 10)) { k = l; } else { k = charToNumber(f); /*This replaces: if (f == 'a') k = 10; if (f == 'b') k = 11; if (f == 'c') k = 12; if (f == 'd') k = 13; if (f == 'e') k = 14; if (f == 'f') k = 15; if (f == 'g') k = 16; if (f == 'h') k = 17; if (f == 'i') k = 18; if (f == 'j') k = 19; if (f == 'k') k = 20; if (f == 'l') k = 21; if (f == 'm') k = 22; if (f == 'n') k = 23; if (f == 'o') k = 24; */ } if (print) { System.out.println(" k = " + k); } newNoteIndex = newNoteIndex + direction * k; newNote = SUPER_ALPHABET.charAt(newNoteIndex); //The new note is assembled z = z + newNote + third; } if (print) { System.out.println("mTIntNotation = " + a + "\n mT in one letter notation = = " + z + "\n"); } return z; } //A musiText in interval notation is rewritten //as a normal ABC musiText. //NOtes occupy even positions, beginning from zero, //and durations odd ones. //Accidents are prefixes in ABC notation. //Sharp is denoted by ^, flat by _ private String interpreter(String ss) { ss = ss.replaceAll("R", "A,"); ss = ss.replaceAll("S", "_B,"); ss = ss.replaceAll("T", "B,"); ss = ss.replaceAll("M", "#C"); ss = ss.replaceAll("M", "#c"); ss = ss.replaceAll("N", "_E"); ss = ss.replaceAll("n", "_e"); ss = ss.replaceAll("O", "^F"); ss = ss.replaceAll("o", "^f"); ss = ss.replaceAll("P", "^G"); ss = ss.replaceAll("p", "^g"); ss = ss.replaceAll("Q", "_B"); ss = ss.replaceAll("q", "_b"); //ss = ss.replaceAll("+", ""); //ss = ss.replaceAll("-", ""); return ss; } //===================== //==== Evolution====== //==================== //Strings that represent ABC tunes //are synthesized at random //selected, recombined, mutated //reproduced. //This is a fair model of evolution: //strings encode for an ABC tune (genotype) //which are listened at by the User (phenotype) //who gives scores to tunes //that direct reproduction. private void printPopulation() { for (int i = 0; i < NUMBER_IND; i++) { System.out.println(Ind[i]); } } //The User assess each tune by giving a score. //ind is a string that encodes for a tune //in one-letter notation. private void playInd(String indNI) { System.out.println(indNI); //A musicText in Interval Notation //is translated into ABC one letter notation //String MusitextOneLetter = transcription(indNI); //ind is translated to ordinary ABC notation //String musiText = interpreter(MusitextOneLetter); //if (print) //System.out.println("MusiText = " + musiText); //An ABC musiText is assembled String musiText = header + indNI; System.out.println("\nmusiText \n" + musiText); //musiText is made into an ABC tune Tune tune; tune = ABCmusiTextToTune(musiText); //The score can eventually be drawn if (drawTune) { DrawTune(tune); } playTune(tune); } //Individuals are sorted by fitness. //The fittest is the first. private void sorting() { if (printThis) { printPopulation(); } int Champ; //FitnessCopy[] is a copy of Fitness[] //used as workbench. double FitnessCopy[] = new double[N_MAX]; for (int i = 0; i < NUMBER_IND; i++) { Fitness[i] = 1000000; FitnessCopy[i] = 1000000; } if (print) { System.out.println("\nSCORING \n"); } for (int i = 0; i < NUMBER_IND; i++) { if (print) { System.out.println("\nind = " + i + " " + Ind[i]); } Fitness[i] = fitnessCol.getCellData(i).doubleValue(); FitnessCopy[i] = Fitness[i]; } if (print) { System.out.println("\nIndividuals and scores "); for (int i = 0; i < NUMBER_IND; i++) { System.out.println("Individual " + i + " = " + Ind[i] + " Score = " + FitnessCopy[i]); } } //We sort individuals by fitness // Fitness 0 means the worst, 5 is perfect if (print) { System.out.println("" + "\nSORTING: from the best to the worst: "); } for (int i = 0; i < NUMBER_IND; i++) { Champ = 0; for (int j = 0; j < NUMBER_IND; j++) { if (FitnessCopy[j] > FitnessCopy[Champ]) { Champ = j; } } //The array Order classifies individuals by fitness. //The fittest is number zero Ordered[i] = Champ; FitnessCopy[Champ] = 0; if (print) { System.out.println("ind number " + Ordered[i] + " " + Ind[Ordered[i]] + " score " + Fitness[Ordered[i]]); } } //IndClone is a copy of Ind System.arraycopy(Ind, 0, IndClone, 0, NUMBER_IND); } //Negative selection: //Fitness determines probability of death. //The probability of dead is higher, //the lower is the fitness. //Death = replacement of individual by "" private void death() { //Min and max are found double min = 100; double max = -100; for (int j = 0; j < NUMBER_IND; j++) { if (Fitness[j] > max) { max = Fitness[j]; } if (Fitness[j] < min) { min = Fitness[j]; } } if (print) { System.out.println( "\nFitness determines death probability"); } //Fitness determines probability of death for (int j = 0; j < NUMBER_IND; j++) { //Death probability y and fitness x are related by: //y = ax +b //y(min) = 1, (the worst must die) //y(max) = 0, (the best must live) //a = 1/(min - max) //b = -a max = -max/(min -max) double probDeath; if ((max - min) == 0) { probDeath = 0.1; } else { probDeath = -Fitness[j] / (max - min) + max / (max - min); } if (print) { System.out.print("ind " + j); System.out.print(" Fitness = " + Fitness[j]); System.out.println(" ProbDeath = " + probDeath); } double p = r.nextDouble(); //Death = replacement of individual by "" if (p <= probDeath) { Ind[j] = ""; } } if (print) { System.out.println("" + "The best ind is number " + Ordered[0]); } } //A not nil random individual is chosen. private int randomIndiv() { boolean cloned = false; int k = 0; while (cloned == false) { k = r.nextInt(NUMBER_IND); if (!("".equals(Ind[k]))) { cloned = true; } } if (print) { System.out.println( " cloned from old ind " + k); } return k; } //The pre-population of the new generation //is built with clones //of living individuals sampled at random //with replacement. private void Reproduction() { if (print) { System.out.println("\nREPRODUCTION\n"); } for (int j = 0; j < NUMBER_IND; j++) { if (print) { System.out.print("New ind " + j); } IndClone[j] = Ind[randomIndiv()]; } //IndClone is copied to Ind System.arraycopy(IndClone, 0, Ind, 0, NUMBER_IND); } //Recombination is enabled. //individual l is recombined with //another taken at random. private String recInd(int l) { //individual l String indl = IndClone[l]; String head; String tail; String recombinant; int m = indl.length(); //Mutation site int m1; //Random site for recombination m1 = r.nextInt(m); //The head is taken from ind l head = indl.substring(0, m1); //Random number int k = r.nextInt(NUMBER_IND); //Partner at random String partner = IndClone[k]; //The tail is taken from the partner tail = partner.substring(m1); //Recombination recombinant = head + tail; if (print) { System.out.println("Indl = " + indl); System.out.println("Head = " + head); System.out.println("Partner = " + partner); System.out.println("Tail = " + tail); System.out.println("Recomb = " + recombinant + "\n"); } return recombinant; } //We found no remedy against recombination: //it is always mortal for the interval notation. private void recombination() { if (print) { System.out.println("\nRECOMBINATION\n"); } //Ind2 is a copy of Ind System.arraycopy(Ind, 0, IndClone, 0, NUMBER_IND); //Ind1 is a recombinant version of Ind2 for (int l = 0; l < NUMBER_IND; l++) { Ind[l] = recInd(l); } } //Returns the interval of a codon private int intervalCodon(String codon) { int output; //System.out.println( "Input (intervalCodon) = + codon); //The first letter is a sign: //the direction of the interval. char c = codon.charAt(0); //The second letter denotes an interval Character f = codon.charAt(1); if (print) { System.out.println("char 0,1 = " + c + " " + f + " "); } //Direction is decoded int direction; if (c == '+') { direction = 1; } else { direction = -1; } //Interval is decoded int l = Character.getNumericValue(f); int k; if ((l >= 0) & (l < 10)) { k = l; } else { k = charToNumber(f); } if (print) { System.out.println(" k = " + k); } output = direction * k; return output; } //The start has the initial note and a duration private String mutateStart(String a) { if (printThis) { System.out.println("input = " + a); } String h = transcription(a); if (printThis) { System.out.println("input T = " + h); } int length = SUPER_ALPHABET.length(); String output; //Mutate note else duration? double f = r.nextDouble(); if (f < 0.5) //note { char s = a.charAt(0); int indexNote = SUPER_ALPHABET.indexOf(s); //An shift is generated Integer shift = r.nextInt(6); String newNote; int newIndex; //To avoid some overflow problems. if ((indexNote + shift > length) || (indexNote + shift > INTERVALS.length()) || (indexNote + shift < 0)) { shift = -shift; } newIndex = indexNote + shift; if (printThis) { System.out.println( " indexNote = " + indexNote + " shift = " + shift + " newIndex = " + newIndex); } newNote = "" + SUPER_ALPHABET.charAt(newIndex); if (printThis) { System.out.println("Old note = " + s + " New note " + newNote); } String codon = a.substring(2, 5); System.out.println("First Codon = " + codon); int interval = intervalCodon(codon); Integer newInterval = interval - shift; //Compensation: indexNote + interval = newIndex + newInterval; if (printThis) { System.out.println( " indexNote = " + indexNote + " shift = " + shift + " interval = " + interval + " newInterval = " + newInterval); } String newI = intToOneLetterNot(newInterval); output = "" + newNote + a.charAt(1) + newI + a.substring(4); if (printThis) { System.out.println("output (note)" + " = " + output); } } else //duration { //Duration is changed output = "" + a.charAt(0) + randomLetter(durationsAlphabet) + a.substring(2); if (printThis) { System.out.println("output (duration)" + " = " + output); } } h = transcription(output); if (print) { System.out.println("output T = " + h); } return output; } //The interval as Integer is transcribed //to one letter notation private String intToOneLetterNot(Integer intInput) { String sign; if (intInput > 0) { sign = "+"; } else { sign = "-"; } intInput = Math.abs(intInput); String newI2 = intInput.toString(); int j = intInput; char newI; if (intInput > 9) { newI = (char) (j + 87); if (printThis) { System.out.println( j + " = " + newI); } newI2 = "" + newI; } /*This replaces the following code: if (intInput == 10) newI2 = "a"; if (intInput == 11) newI2 = "b"; if (intInput == 12) newI2 = "c"; if (intInput == 13) newI2 = "d"; if (intInput == 14) newI2 = "e"; if (intInput == 15) newI2 = "f"; if (intInput == 16) newI2 = "g"; if (intInput == 17) newI2 = "h"; if (intInput == 18) newI2 = "i"; if (intInput == 19) newI2 = "j"; if (intInput == 20) newI2 = "k"; if (intInput == 21) newI2 = "l"; if (intInput == 22) newI2 = "m"; if (intInput == 23) newI2 = "n"; if (intInput == 24) newI2 = "o" + "" + ""; */ String output = sign + newI2; return output; } //The string a is mutated at two contiguous sites. //Why? We use musiTexts in interval notation, //instructions to rise or lower pitch so, //a mutation may cause notes to get outside //established sets. //The remedy is to make balancing changes at two //contiguous sites in such a way that no harm //is caused beyond mutation site. //Example 1: INTERVALS are mutated //input B6+01-y1+61-41+91-41+01 //output: B6+01-y1+61-21+71-41+01 //Notice: -4 + 9 = 5 = -2 + 7. //Example 2: durations are mutated //input B6+01-y1+61-41+91-41+01 //output: B6+01-y1+61-43+91-41+01 //Notice: we pose no restriction on durations //Example 3: initial note mutated //input B6+01-y1+61-41+91-41+01 //output: A6+21-y1+61-21+71-41+01 //Notice: from B to A there are 2 semitones which are //reestablished in the following note. //The string is divided in three regions: //head + mutation sites + tail. private String twoPointsMutationInd(String a) { if (printThis) { System.out.println( "\nInput string = " + a); } boolean mutateInterval = false; boolean mutateDuration = false; int m = a.length(); String output = ""; if (m == 0) { return output; } else { int l = r.nextInt(a.length()); if (printThis) { System.out.println( "Place mutation = " + l); } //Is l at the beginning? if (l < 2) { output = mutateStart(a); } else //pick codon and mutate it. { int numberCodon1 = (l - 2) / 3; int numberCodons = (m - 2) / 3; int beginCodon1 = numberCodon1 * 3 + 2; int endCodon1 = beginCodon1 + 3; String codon1 = a.substring(beginCodon1, endCodon1); if (printThis) { System.out.println("codon1 = " + codon1 + " codon number = " + numberCodon1 + " Number of codons = " + numberCodons + " a.length = " + m + " endCodon = " + endCodon1); } //Mutate interval else duration? double f = r.nextDouble(); if (printThis) { System.out.println("f = " + f); } if (f < 0.5) { mutateDuration = true; } else { mutateInterval = true; } if (mutateDuration) { //Duration is changed output = "" + a.substring(0, beginCodon1 + 2) + randomLetter(durationsAlphabet) + a.substring(beginCodon1 + 3); if (printThis) { System.out.println( "Output (duration) = " + output + "\n"); } return output; } if (mutateInterval) { int interval1 = intervalCodon(codon1); Integer newInterval1 = 0; if (interval1 > 1) { newInterval1 = r.nextInt(interval1) % 6; } String newInt1 = intToOneLetterNot(newInterval1); output = "" + a.substring(0, beginCodon1) + newInt1 + a.substring(beginCodon1 + 2); if (printThis) { System.out.println( "\n newInterval1 = " + newInterval1 + "\n" + "Output (u) = " + output + "\n"); } //Is codon1 the final one? //Yes = end work if (numberCodon1 == numberCodons - 1) { return output; } else //No: make a coordinate mutation in next site { String codon2 = a.substring(endCodon1, endCodon1 + 3); if (printThis) { System.out.println("Codon 2= " + codon2); } int interval2 = intervalCodon(codon2); //Compensation: Integer newInterval2 = interval1 + interval2 - newInterval1; if (printThis) { System.out.println( " int 1 = " + interval1 + " int 2 = " + interval2 + " newInterval1 = " + newInterval1 + " newInterval2 = " + newInterval2); } String newI2 = intToOneLetterNot(newInterval2); output = "" + output.substring(0, endCodon1) + newI2 + output.substring(endCodon1 + 2); if (printThis) { System.out.println( "Output (interval) = " + output + "\n"); } }//end else } } String h1 = transcription(a); String h2 = transcription(output); if (printThis) { System.out.println( "Input (twoPointsM) = " + a + "\n" + "Output (twoPointsM) = " + output + "\n" + "Input (twoPointsM) = " + h1 + "\n" + "Output (twoPointsM) = " + h2 + "\n"); } return output; }//End no void input }//end method //All strings are mutated. private void mutation() { if (print) { System.out.println("\nMUTATION\n"); } // All the individuals mutate. for (int j = 0; j < NUMBER_IND; j++) { //v=original individual String v = Ind[j]; // w = mutated individual. String w = twoPointsMutationInd(v); Ind[j] = w; //Replacement } } private void readTable() { for (int i = 0; i < NUMBER_IND; i++) { Integer d = table.getItems().get(i).fitness.getValue(); String s = table.getItems().get(i).chromosome.getValue(); System.out.println(d + " " + s); } } private void updateTable() { for (int i = 0; i < NUMBER_IND; i++) { String s = interpreter(transcription(Ind[i])); Item item = new Item(s, (int) Fitness[i]); table.getItems().set(i, item); } } //Evolution = selection + reproduction //+recombination + mutation private void Dynamics() { System.out.println("\nGENERATION = " + generation + " \n"); sorting(); death(); Reproduction(); mutation(); //recombination(); updateTable(); } //Evolution is made into a co-composer public void nextGeneration() { generation++; Dynamics(); } public void showInformation(String title, String message) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.initStyle(StageStyle.UTILITY); alert.setTitle(title); alert.setHeaderText(title); alert.setContentText(message); alert.showAndWait(); } }//End of EvoMusic5 }//End of main class Finch //================================= /* X:14 T:Canción de cuna M:4/4 L:1/8 K:C C>CCEG2G2 | A>AAAG4 | FFF FE2E2 | D> D DDC4 | C>CCEG2G2 | A>AAAG4 | EGE GD2D2 | E> F EDC4 | C/2z/2CCEG2G2 | A>AAAG4 | E^FG E^F2D2 | ^C D E^CD4 | FEE DD2C2 | E< F GBc4 |] */ /* * X:14 T:Canción de cuna M:4/4 L:1/8 K:C C>CCEG2G2 | w:A-rru-rrú mi ni-ña, A>AAAG4 | w:a-rru-rrú mi sol, FFF FE2E2 | D> D DDC4 | w:duér-me-te pe-da-zo de mi co-ra-zón. C>CCEG2G2 | w:Van pa-san-do nu-bes, A>AAAG4 | w:co-pos de.al-go-dón, EGE GD2D2 | E> F EDC4 | w:duér-me-te pe-da-zo de mi co-ra-zón. C/2z/2CCEG2G2 | w:Pa-lo-mi-tas vie-nen, A>AAAG4 | w:pa-lo-mi-tas van, E^FG E^F2D2 | ^C D E^CD4 | w:duér-me-te pe-da-zo de mi co-ra-zón. FEE DD2C2 | E< F GBc4 |] w:Duér-me-te pe-da-zo de mi co-ra-zón.*/ /* * * Level of complexity 6 (6 notes): 5/III/2013: Today I have been very bad, the most I could made was a run of 11 good points and another of 10. It seems that notes began to sound like aliens and only after some 100 trials they began to sound almost normally. So, the neural mechanisms is in principle not tuned to notes but to INTERVALS. Or what? Bit by bit they learn in each session to discriminate notes separately. 7/III/2013 Perceived sound of a note is NOT constant. It seems to depend on the previous played notes. 14/III/2013 There are moments, 2 minutes long, when everything gets clear and notes are distinct as day is from night. But these are transient and gave their place to other moments full in confusion. 16/III/2013 Notes are perceived different along their duration, so they must be consciously analyzed. This improves percentage of success. 21/III I feel as if I am almost done. 28/III One needs to warm the pattern recognizer: it is not addressed to distinguish do from Re but rather it is a discriminating mechanism targeted at many diverse sounds. 22/IV I ceased training during some 15 days. When I returned back to work my level was found to had lost its fine tuning. 27/IV I feel that I am regaining fine tuning and I was able to reach a run of 23 successes. 8/V It seems that I am returning to my previous level but not yet fully. 8/VI/ I feel trapped inside of an strange attractor: I turn over and over and progress is not made. 12/VI After a period of indiscipline, I had a very bad beginning but at the end of my session I felt much better. 14/VI Unexpectedly I passed to the next level. 29/VI: NEW LEVEL 7 Everything was easy while tolerance was not zero. Afterwards, suffering began. 6/VII The worst day of all. 8/VII Lost in the jungle. 19/VII I feel better: I have arrived various times to runs with 10 successes in line. 31/VII After 5 days of no practice, performance was too bad. 22/VIII/ I made 24 points in a run. First time in this level. 20/XI/ Today I arrived at the 20000th trial in my level with 7 notes. Today I achieved a run of 25 good points. For moments I see a light in the distance. Sometimes it seems that concentration is everything to success but at other times I feel myself completely lost. And it is not because lack of practice. 21/XI 34 points in a run up to a target for 49, I committed an error and collapsed: no more long runs. 3/XII The most astonishing for me fact along this work is that notes do not sound the same every time. This implies that consciousness is not that far from the neural networks that process information from senses. But, why is perception so unstable? This happens because senses are implemented as physical units that might or not be shielded against a perturbation of the milieu. It seems that hearing transducers are not shielded and so their overall performance heavily depends on the physical situation as of the outer environment as of the inner one. Say, a change in temperature causes a change in the transducers that transform sound into neural signals. Bad remembrances also produces shifts but for me it has been difficult to understand if this is or not due to a lost of attention. So, a change in the environment is followed by a change in output for the same input plus restructuring of networks to look for a better performance. The overall effect is that notes may sound different in different times. A question arises: why and how is the consciousness of sound perceived as distinct than the perception of sound? 13/XII/ The worst day. 8/I/2014 After 20 days of rest, I achieved a maximal run of 11. 15/I/2014 Maximal run = 19. Today I arrived to the trial 25000. Parameters: Tenacity = expertise = complexity = 7. By moments I feel like a principiant. 22/I I passed the barrier of the 20 good points for the first time in this year. 3/II The best day: I arrived to 32 points in line (target = 49). 15/III Today I arrived to the trial 33333. My top run was 13. 12/V Trial number 40000. My best run was 16. Rarely I have surpassed this MARK in the last days. 17/VI Unexpectedly I arrived today to 39 good points of 49 in line. 30/VI 44 good points in line. 2/VII Today I passed over the trial 50000. My best run was 24 good points in line. I made 224 trials and my efficiency was 0.80. I became aware yesterday that the perception of the span of the interval of sounds was small at the beginning and then got wider. So, it became easier to distinguish differences. 6/VII Best run: 44 good points in line 18/VIII After a hot coffee against the cold weather and wind, I lost any contact with pitch recognizing: my top run was 6. 25/VIII My top run was 11. I blame the intense cold and wind through the window that interferes directly with my sense of hearing. 15/X Almost 60000 trials and I remain in the same level: around 20 points in a line of 49. I fell that I am wandering with no improvement. So, I have decided to change my strategy: I am going to use the possibbility to compare the given note with the notes played as a hint. I have tried this before but unsuccessfully. First trials have shown that my ear has matured a bit so, this hint is expected to help me. This has a cost: from 200 trials per session, I fell down to 50. 5/XI Today I did my level with 6 NOTAS at trial 61011. While I was unable to pass to the next level during 60000 trials, I was able of doing that after other 1000 trials when I used the hint given by the program: to listen at all NOTES in the level. 13/XII I passed today to next level with 8 notes. I was able to use the help of listening to the sequence of notes to detect the testing note. This is a surprise because earlier attempts showed me that I was wandering anew under a chaotic regime. 13/I/2015 After some 10 days of no practice, It seems that I lost previously acquired skills. After two days, my best run has been 14. 26/V Strong tendinities. Decision: no more than 100 trials per day. 17/XI Wandering around very bad performance. I/2016 It seems that I am taking off beyond a series of 10 good points. III/2016 I feel a kind of maduration. Bug = dos veces training = bug. Falta decir cuántos trials faltan save and end session only valid for training not in general.! 11/July:2017 I arrived to 28 points. First time in many months. 11/XI/2017; I arrived to 34/64 points. My regular score was less than 20. Performance of the Author: June 2 2016 7 7 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 6 7 10 6 6 6 6 8 8 9 8 8 8 9 8 16 12 16 13 12 14 14 962 42 60 56 67 107 150 2168 19036 66 62 70 74 66 70 230 61011 64 62 68 61 68 65 66 803 184 109 100 149 141 289 78 25815 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 September 21/2017 7 7 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 6 7 10 6 6 6 6 8 8 9 8 8 8 9 8 16 12 16 13 12 14 14 962 42 60 56 67 107 150 2168 19036 66 62 70 74 66 70 230 61011 64 62 68 61 68 65 66 803 184 109 100 149 141 289 78 50999 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 */ /* Piano key frequencies From Wikipedia, the free encyclopedia (Redirected from Frequencies of notes) This is a list of the absolute frequencies in hertz (cycles per second) of the keys of a standard modern 88-key piano in twelve-tone equal temperament, with the 49th key, the fifth A (called A4), tuned to 440 Hz (referred to as A440). Each successive pitch is derived by multiplying (ascending) or dividing (descending) the previous by the twelfth root of two (approximately 1.05946...). For example, to get the frequency a semitone up from A4 (A♯4), multiply 440 by the twelfth root of two. To go from A4 to B4 (up a whole tone, or two semitones), multiply 440 twice by the twelfth root of two. For other tuning schemes refer to musical tuning. This list of frequencies is for a theoretically ideal piano. On an actual piano the ratio between semitones is slightly larger, especially at the high and low ends, where string stiffness causes inharmonicity, i.e., the tendency for the harmonic makeup of each note to run sharp. To compensate for this, octaves are tuned slightly wide, stretched according to the inharmonic characteristics of each instrument. This deviation from equal temperament is called the Railsback curve. The following equation gives the frequency f of the nth key, as shown in the table: f(n) = (\sqrt[12]{2}\,)^{n-49} \times 440 \,\text{Hz}\, (a' = A4 = A440 is the 49th key on the idealized piano) Alternatively, this can be written as: f(n) = 2^{\frac{n-49}{12}} \times 440 \,\text{Hz}\, Conversely, starting from a frequency on the idealized piano tuned to A440, one obtains the key number by: n = 12 \, \log_2\left({\frac{f}{440 \,\text{Hz}}}\right) + 49 List Piano Keyboard An 88-key piano, with the octaves numbered and Middle C (cyan) and A440 (yellow) highlighted. A printable version of the chart below. Key number Helmholtz name Scientific name Frequency (Hz) Corresponding Open Strings Violin Viola Cello Bass Guitar 88 c′′′′′ 5-line octave C8 Eighth octave 4186.01 87 b′′′′ B7 3951.07 86 a♯′′′′/b♭′′′′ A♯7/B♭7 3729.31 85 a′′′′ A7 3520.00 84 g♯′′′′/a♭′′′′ G♯7/A♭7 3322.44 83 g′′′′ G7 3135.96 82 f♯′′′′/g♭′′′′ F♯7/G♭7 2959.96 81 f′′′′ F7 2793.83 80 e′′′′ E7 2637.02 79 d♯′′′′/e♭′′′′ D♯7/E♭7 2489.02 78 d′′′′ D7 2349.32 77 c♯′′′′/d♭′′′′ C♯7/D♭7 2217.46 76 c′′′′ 4-line octave C7 Double high C 2093.00 75 b′′′ B6 1975.53 74 a♯′′′/b♭′′′ A♯6/B♭6 1864.66 73 a′′′ A6 1760.00 72 g♯′′′/a♭′′′ G♯6/A♭6 1661.22 71 g′′′ G6 1567.98 70 f♯′′′/g♭′′′ F♯6/G♭6 1479.98 69 f′′′ F6 1396.91 68 e′′′ E6 1318.51 67 d♯′′′/e♭′′′ D♯6/E♭6 1244.51 66 d′′′ D6 1174.66 65 c♯′′′/d♭′′′ C♯6/D♭6 1108.73 64 c′′′ 3-line octave C6 Soprano C (High C) 1046.50 63 b′′ B5 987.767 62 a♯′′/b♭′′ A♯5/B♭5 932.328 61 a′′ A5 880.000 60 g♯′′/a♭′′ G♯5/A♭5 830.609 59 g′′ G5 783.991 58 f♯′′/g♭′′ F♯5/G♭5 739.989 57 f′′ F5 698.456 56 e′′ E5 659.255 E 55 d♯′′/e♭′′ D♯5/E♭5 622.254 54 d′′ D5 587.330 53 c♯′′/d♭′′ C♯5/D♭5 554.365 52 c′′ 2-line octave C5 523.251 51 b′ B4 493.883 50 a♯′/b♭′ A♯4/B♭4 466.164 49 a′ A4 A440 440.000 A A High A (Optional) 48 g♯′/a♭′ G♯4/A♭4 415.305 47 g′ G4 391.995 46 f♯′/g♭′ F♯4/G♭4 369.994 45 f′ F4 349.228 44 e′ E4 329.628 High E 43 d♯′/e♭′ D♯4/E♭4 311.127 42 d′ D4 293.665 D D 41 c♯′/d♭′ C♯4/D♭4 277.183 40 c′ 1-line octave C4 Middle C 261.626 39 b B3 246.942 B 38 a♯/b♭ A♯3/B♭3 233.082 37 a A3 220.000 A 36 g♯/a♭ G♯3/A♭3 207.652 35 g G3 195.998 G G G 34 f♯/g♭ F♯3/G♭3 184.997 33 f F3 174.614 F (7 string) 32 e E3 164.814 31 d♯/e♭ D♯3/E♭3 155.563 30 d D3 146.832 D D 29 c♯/d♭ C♯3/D♭3 138.591 28 c small octave C3 Tenor C 130.813 C (5 string) C C (6 string) 27 B B2 123.471 26 A♯/B♭ A♯2/B♭2 116.541 25 A A2 110.000 A 24 G♯/A♭ G♯2/A♭2 103.826 23 G G2 97.9989 G G 22 F♯/G♭ F♯2/G♭2 92.4986 21 F F2 87.3071 F (6 string) 20 E E2 82.4069 Low E 19 D♯/E♭ D♯2/E♭2 77.7817 18 D D2 73.4162 D 17 C♯/D♭ C♯2/D♭2 69.2957 16 C great octave C2 Deep C 65.4064 C 15 B͵ B1 61.7354 B (7 string) 14 A♯͵/B♭͵ A♯1/B♭1 58.2705 B♭ (7 string) 13 A͵ A1 55.0000 A 12 G♯͵/A♭͵ G♯1/A♭1 51.9131 11 G͵ G1 48.9994 10 F♯͵/G♭͵ F♯1/G♭1 46.2493 F♯ (8 string) 9 F͵ F1 43.6535 8 E͵ E1 41.2034 E 7 D♯͵/E♭͵ D♯1/E♭1 38.8909 6 D͵ D1 36.7081 5 C♯͵/D♭͵ C♯1/D♭1 34.6478 C♯ (9 string) 4 C͵ contra-octave C1 Pedal C 32.7032 3 B͵͵ B0 30.8677 B (5 string) 2 A♯͵͵/B♭͵͵ A♯0/B♭0 29.1352 1 A͵͵ sub-contra-octave A0 Double Pedal A 27.5000 */ //Task: the date in the file must be the date when the last table was saved. //Task2: playing training notes must be shown in in the pane.