repo
string
commit
string
message
string
diff
string
sfraser/MultithreadedGameOfLife
0fea7575573a8a2d0bec798b51880fe3d1351d44
opened in IntelliJ 9.0.1 added comment about transients
diff --git a/MultithreadedGameOfLife.ipr b/MultithreadedGameOfLife.ipr index af63655..21e41f6 100644 --- a/MultithreadedGameOfLife.ipr +++ b/MultithreadedGameOfLife.ipr @@ -1,260 +1,218 @@ <?xml version="1.0" encoding="UTF-8"?> -<project relativePaths="false" version="4"> +<project version="4"> <component name="AntConfiguration"> <defaultAnt bundledAnt="true" /> </component> <component name="BuildJarProjectSettings"> <option name="BUILD_JARS_ON_MAKE" value="false" /> </component> - <component name="CodeStyleSettingsManager"> - <option name="PER_PROJECT_SETTINGS" /> - <option name="USE_PER_PROJECT_SETTINGS" value="false" /> - </component> <component name="CompilerConfiguration"> <option name="DEFAULT_COMPILER" value="Javac" /> - <option name="DEPLOY_AFTER_MAKE" value="0" /> <resourceExtensions> <entry name=".+\.(properties|xml|html|dtd|tld)" /> <entry name=".+\.(gif|png|jpeg|jpg)" /> </resourceExtensions> <wildcardResourcePatterns> <entry name="?*.properties" /> <entry name="?*.xml" /> <entry name="?*.gif" /> <entry name="?*.png" /> <entry name="?*.jpeg" /> <entry name="?*.jpg" /> <entry name="?*.html" /> <entry name="?*.dtd" /> <entry name="?*.tld" /> <entry name="?*.ftl" /> </wildcardResourcePatterns> + <annotationProcessing enabled="false" useClasspath="true" /> </component> <component name="CopyrightManager" default=""> <module2copyright /> </component> <component name="DependencyValidationManager"> <option name="SKIP_IMPORT_STATEMENTS" value="false" /> </component> <component name="EclipseCompilerSettings"> - <option name="DEBUGGING_INFO" value="true" /> <option name="GENERATE_NO_WARNINGS" value="true" /> <option name="DEPRECATION" value="false" /> - <option name="ADDITIONAL_OPTIONS_STRING" value="" /> - <option name="MAXIMUM_HEAP_SIZE" value="128" /> </component> <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" /> <component name="IdProvider" IDEtalkID="B68953F18167018093CC8C1CA8D72796" /> - <component name="InspectionProjectProfileManager"> - <option name="PROJECT_PROFILE" value="Project Default" /> - <option name="USE_PROJECT_LEVEL_SETTINGS" value="false" /> - <scopes /> - <profiles> - <profile version="1.0" is_locked="false"> - <option name="myName" value="Project Default" /> - <option name="myLocal" value="false" /> - </profile> - </profiles> - <list size="0" /> - </component> - <component name="JavacSettings"> - <option name="DEBUGGING_INFO" value="true" /> - <option name="GENERATE_NO_WARNINGS" value="false" /> - <option name="DEPRECATION" value="true" /> - <option name="ADDITIONAL_OPTIONS_STRING" value="" /> - <option name="MAXIMUM_HEAP_SIZE" value="128" /> - </component> <component name="JavadocGenerationManager"> <option name="OUTPUT_DIRECTORY" /> <option name="OPTION_SCOPE" value="protected" /> <option name="OPTION_HIERARCHY" value="true" /> <option name="OPTION_NAVIGATOR" value="true" /> <option name="OPTION_INDEX" value="true" /> <option name="OPTION_SEPARATE_INDEX" value="true" /> <option name="OPTION_DOCUMENT_TAG_USE" value="false" /> <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" /> <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" /> <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" /> <option name="OPTION_DEPRECATED_LIST" value="true" /> <option name="OTHER_OPTIONS" value="" /> <option name="HEAP_SIZE" /> <option name="LOCALE" /> <option name="OPEN_IN_BROWSER" value="true" /> </component> - <component name="JikesSettings"> - <option name="JIKES_PATH" value="" /> - <option name="DEBUGGING_INFO" value="true" /> - <option name="DEPRECATION" value="true" /> - <option name="GENERATE_NO_WARNINGS" value="false" /> - <option name="IS_EMACS_ERRORS_MODE" value="true" /> - <option name="ADDITIONAL_OPTIONS_STRING" value="" /> - </component> <component name="Palette2"> <group name="Swing"> <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" /> </item> <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" /> </item> <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" /> </item> <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true"> <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" /> </item> <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" /> <initial-values> <property name="text" value="Button" /> </initial-values> </item> <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> <initial-values> <property name="text" value="RadioButton" /> </initial-values> </item> <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> <initial-values> <property name="text" value="CheckBox" /> </initial-values> </item> <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" /> <initial-values> <property name="text" value="Label" /> </initial-values> </item> <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" /> </item> <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> <preferred-size width="200" height="200" /> </default-constraints> </item> <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> <preferred-size width="200" height="200" /> </default-constraints> </item> <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> </item> <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> </item> <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" /> </item> <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" /> </item> <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1"> <preferred-size width="-1" height="20" /> </default-constraints> </item> <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" /> </item> <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" /> </item> </group> </component> <component name="ProjectDetails"> <option name="projectName" value="MultithreadedGameOfLife" /> </component> - <component name="ProjectFileVersion" converted="true" /> <component name="ProjectKey"> <option name="state" value="project:///home/sfraser/IdeaProjects/MultithreadedGameOfLife/MultithreadedGameOfLife.ipr" /> </component> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/MultithreadedGameOfLife.iml" filepath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" /> </modules> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_5" assert-keyword="true" jdk-15="true" project-jdk-name="1.6 (1)" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/out" /> </component> <component name="ResourceManagerContainer"> <option name="myResourceBundles"> <value> <list size="0" /> </value> </option> </component> - <component name="RmicSettings"> - <option name="IS_EANABLED" value="false" /> - <option name="DEBUGGING_INFO" value="true" /> - <option name="GENERATE_NO_WARNINGS" value="false" /> - <option name="GENERATE_IIOP_STUBS" value="false" /> - <option name="ADDITIONAL_OPTIONS_STRING" value="" /> - </component> <component name="SvnBranchConfigurationManager"> <option name="myVersion" value="124" /> <option name="mySupportsUserInfoFilter" value="true" /> </component> <component name="VcsDirectoryMappings"> <mapping directory="" vcs="Git" /> </component> <component name="WebServicesPlugin" addRequiredLibraries="true" /> <component name="libraryTable"> <library name="clojure-1.0"> <CLASSES> <root url="jar://$PROJECT_DIR$/lib/clojure.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component> </project> diff --git a/MultithreadedGameOfLife.iws b/MultithreadedGameOfLife.iws index a4fbc06..1e556c8 100644 --- a/MultithreadedGameOfLife.iws +++ b/MultithreadedGameOfLife.iws @@ -1,657 +1,616 @@ <?xml version="1.0" encoding="UTF-8"?> -<project relativePaths="false" version="4"> +<project version="4"> <component name="CCaseConfig"> <option name="checkoutReserved" value="false" /> <option name="markExternalChangeAsUpToDate" value="true" /> <option name="checkInUseHijack" value="true" /> <option name="useUcmModel" value="true" /> <option name="isOffline" value="false" /> <option name="synchOutside" value="false" /> <option name="isHistoryResticted" value="true" /> <option name="useIdenticalSwitch" value="true" /> <option name="synchActivitiesOnRefresh" value="true" /> <option name="lastScr" value="" /> <option name="scrTextFileName" value="" /> <option name="historyRevisionsNumber" value="4" /> </component> - <component name="ChangeListManager"> - <list default="true" name="Default" comment=""> + <component name="ChangeListManager" verified="true"> + <list default="true" id="52be9b1e-d39d-48b5-b96d-bf188d1fbe5a" name="Default" comment=""> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.ipr" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.ipr" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" afterPath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> </list> <ignored path=".idea/workspace.xml" /> <ignored path="MultithreadedGameOfLife.iws" /> + <option name="TRACKING_ENABLED" value="true" /> + <option name="SHOW_DIALOG" value="false" /> + <option name="HIGHLIGHT_CONFLICTS" value="true" /> + <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> + <option name="LAST_RESOLUTION" value="IGNORE" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="Commander"> <leftPanel /> <rightPanel /> <splitter proportion="0.5" /> </component> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> <option name="REVERSE_PATCH" value="false" /> </component> <component name="DaemonCodeAnalyzer"> <disable_hints /> </component> <component name="DebuggerManager"> <breakpoint_any> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> </breakpoint_any> <breakpoint_rules /> <ui_properties /> </component> <component name="FavoritesManager"> <favorites_list name="MultithreadedGameOfLife" /> </component> + <component name="FileColors" enabled="true" enabledForTabs="true" /> <component name="FileEditorManager"> - <splitter split-orientation="vertical" split-proportion="0.5591111"> - <split-first> - <leaf> - <file leaf-file-name="MultiThreadedLife.clj" pinned="false" current="false" current-in-tab="true"> - <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> - <provider selected="true" editor-type-id="text-editor"> - <state line="234" column="22" selection-start="12863" selection-end="12863" vertical-scroll-proportion="1.0634615"> - <folding /> - </state> - </provider> - </entry> - </file> - <file leaf-file-name="README" pinned="false" current="false" current-in-tab="false"> - <entry file="file://$PROJECT_DIR$/src/README"> - <provider selected="true" editor-type-id="text-editor"> - <state line="1" column="28" selection-start="29" selection-end="29" vertical-scroll-proportion="0.0"> - <folding /> - </state> - </provider> - </entry> - </file> - </leaf> - </split-first> - <split-second> - <leaf> - <file leaf-file-name="README" pinned="false" current="true" current-in-tab="true"> - <entry file="file://$PROJECT_DIR$/src/README"> - <provider selected="true" editor-type-id="text-editor"> - <state line="19" column="10" selection-start="1202" selection-end="1202" vertical-scroll-proportion="0.67058825"> - <folding /> - </state> - </provider> - </entry> - </file> - </leaf> - </split-second> - </splitter> + <leaf> + <file leaf-file-name="README" pinned="false" current="true" current-in-tab="true"> + <entry file="file://$PROJECT_DIR$/README"> + <provider selected="true" editor-type-id="text-editor"> + <state line="22" column="131" selection-start="1244" selection-end="1244" vertical-scroll-proportion="0.37844038"> + <folding /> + </state> + </provider> + </entry> + </file> + </leaf> </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="false" /> </FindUsagesManager> </component> <component name="ModuleEditorState"> <option name="LAST_EDITED_MODULE_NAME" /> <option name="LAST_EDITED_TAB_NAME" /> </component> + <component name="ProjectInspectionProfilesVisibleTreeState"> + <entry key="Project Default"> + <profile-state /> + </entry> + </component> <component name="ProjectLevelVcsManager"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <OptionsSetting value="true" id="Undo Check Out" /> <OptionsSetting value="true" id="Get Latest Version" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="Libraries" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.LibraryGroupNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="src" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="life" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> </PATH> </subPane> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> - <navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5"> + <navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> - <showStructure ProjectPane="false" /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> + <panes> + <pane id="PackagesPane" /> + <pane id="Favorites" /> + <pane id="ProjectPane"> + <subPane> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + </PATH> + </subPane> + </pane> + <pane id="Scope" /> + </panes> </component> <component name="PropertiesComponent"> <property name="project.structure.last.edited" value="Modules" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="82" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="119" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="402" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="439" /> <property name="project.structure.proportion" value="0.15" /> <property name="options.splitter.main.proportions" value="0.3" /> <property name="RunManagerConfig.showSettingsBeforeRunnig" value="true" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder1" value="1" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="94" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="414" /> <property name="MemberChooser.sorted" value="false" /> + <property name="recentsLimit" value="5" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder0" value="0" /> - <property name="last_opened_file_path" value="/home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="103" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="897" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="893" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="99" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="115" /> + <property name="last_opened_file_path" value="$PROJECT_DIR$/../../NetBeansProjects/ClojureLife/src/org/frasers/life" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="423" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="1217" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="1213" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="419" /> + <property name="GoToClass.includeJavaFiles" value="false" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="435" /> <property name="GoToClass.toSaveIncludeLibraries" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder2" value="2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder3" value="3" /> <property name="MemberChooser.showClasses" value="true" /> <property name="GoToClass.includeLibraries" value="false" /> <property name="options.splitter.details.proportions" value="0.2" /> - <property name="GoToFile.includeJavaFiles" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder0" value="0" /> + <property name="GoToFile.includeJavaFiles" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder3" value="3" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder1" value="1" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder2" value="2" /> - <property name="options.lastSelected" value="com.intellij.openapi.vcs.configurable.VcsManagerConfigurable$4" /> + <property name="options.lastSelected" value="preferences.pluginManager" /> <property name="project.structure.side.proportion" value="0.2" /> <property name="MemberChooser.copyJavadoc" value="false" /> <property name="dynamic.classpath" value="false" /> <property name="options.searchVisible" value="true" /> </component> <component name="RegexUtilComponent" text="1900-01-01 2007/08/13 1900.01.01 1900 01 01 1900-01.01 1900 13 01 1900 02 31" mode="0" flags="0" regex="(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])" /> - <component name="RunManager" selected="Clojure Script.MultiThreadedLife"> + <component name="RunManager"> <configuration default="true" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="" /> <setting name="path" value="" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="" /> <setting name="repl" value="false" /> + <method> + <option name="BuildArtifacts" enabled="false" /> + <option name="Make" enabled="true" /> + </method> </configuration> <configuration default="true" type="Remote" factoryName="Remote"> <option name="USE_SOCKET_TRANSPORT" value="true" /> <option name="SERVER_MODE" value="false" /> <option name="SHMEM_ADDRESS" value="javadebug" /> <option name="HOST" value="localhost" /> <option name="PORT" value="5005" /> - </configuration> - <configuration default="true" type="TestNG" factoryName="TestNG" enabled="false" merge="false" runner="emma"> - <module name="" /> - <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> - <option name="ALTERNATIVE_JRE_PATH" /> - <option name="SUITE_NAME" /> - <option name="PACKAGE_NAME" /> - <option name="MAIN_CLASS_NAME" /> - <option name="METHOD_NAME" /> - <option name="GROUP_NAME" /> - <option name="TEST_OBJECT" value="CLASS" /> - <option name="VM_PARAMETERS" /> - <option name="PARAMETERS" /> - <option name="WORKING_DIRECTORY" /> - <option name="OUTPUT_DIRECTORY" /> - <option name="ANNOTATION_TYPE" /> - <option name="ENV_VARIABLES" /> - <option name="PASS_PARENT_ENVS" value="true" /> - <option name="ADDITIONAL_CLASS_PATH" /> - <option name="TEST_SEARCH_SCOPE"> - <value defaultName="moduleWithDependencies" /> - </option> - <option name="PROPERTIES_FILE" /> - <envs /> - <properties /> - <listeners /> + <method> + <option name="BuildArtifacts" enabled="false" /> + </method> </configuration> <configuration default="true" type="Applet" factoryName="Applet"> <module name="" /> <option name="MAIN_CLASS_NAME" /> <option name="HTML_FILE_NAME" /> <option name="HTML_USED" value="false" /> <option name="WIDTH" value="400" /> <option name="HEIGHT" value="300" /> <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" /> <option name="VM_PARAMETERS" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> + <method> + <option name="BuildArtifacts" enabled="false" /> + <option name="Make" enabled="true" /> + </method> </configuration> - <configuration default="true" type="Application" factoryName="Application" enabled="false" merge="false" runner="emma"> + <configuration default="true" type="Application" factoryName="Application"> + <extension name="coverage" enabled="false" merge="false" runner="emma" /> + <extension name="snapshooter" /> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> + <method> + <option name="BuildArtifacts" enabled="false" /> + <option name="Make" enabled="true" /> + </method> </configuration> - <configuration default="true" type="JUnit" factoryName="JUnit" enabled="false" merge="false" runner="emma"> + <configuration default="true" type="JUnit" factoryName="JUnit"> + <extension name="coverage" enabled="false" merge="false" runner="emma" /> + <extension name="snapshooter" /> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="TEST_OBJECT" value="class" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> - <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <envs /> + <method> + <option name="BuildArtifacts" enabled="false" /> + <option name="Make" enabled="true" /> + </method> </configuration> <configuration default="false" name="MultiThreadedLife" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="MultithreadedGameOfLife" /> <setting name="path" value="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="$PROJECT_DIR$/src/org/frasers/life" /> <setting name="repl" value="false" /> <RunnerSettings RunnerId="JProfiler"> <option name="WINDOW" value="false" /> <option name="JVMPI" value="false" /> <option name="INTERPRETED" value="false" /> </RunnerSettings> <RunnerSettings RunnerId="Run" /> <ConfigurationWrapper RunnerId="JProfiler" /> <ConfigurationWrapper RunnerId="Run" /> - <method> - <option name="Make" value="true" /> - </method> + <method /> </configuration> <list size="1"> <item index="0" class="java.lang.String" itemvalue="Clojure Script.MultiThreadedLife" /> </list> <configuration name="&lt;template&gt;" type="WebApp" default="true" selected="false"> <Host>localhost</Host> <Port>5050</Port> </configuration> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="StarteamConfiguration"> <option name="SERVER" value="" /> <option name="PORT" value="49201" /> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="PROJECT" value="" /> <option name="VIEW" value="" /> <option name="ALTERNATIVE_WORKING_PATH" value="" /> <option name="LOCK_ON_CHECKOUT" value="false" /> <option name="UNLOCK_ON_CHECKIN" value="false" /> </component> <component name="StructureViewFactory"> - <option name="AUTOSCROLL_MODE" value="true" /> - <option name="AUTOSCROLL_FROM_SOURCE" value="false" /> <option name="ACTIVE_ACTIONS" value="ALPHA_COMPARATOR" /> </component> <component name="SvnConfiguration"> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="LAST_MERGED_REVISION" /> <option name="UPDATE_RUN_STATUS" value="false" /> <option name="MERGE_DRY_RUN" value="false" /> <option name="MERGE_DIFF_USE_ANCESTRY" value="true" /> <option name="UPDATE_LOCK_ON_DEMAND" value="false" /> <option name="IGNORE_SPACES_IN_MERGE" value="false" /> - <configuration useDefault="true">/home/sfraser/.subversion</configuration> + <configuration useDefault="true">$PROJECT_DIR$/../../.subversion</configuration> <myIsUseDefaultProxy>false</myIsUseDefaultProxy> <supportedVersion>125</supportedVersion> </component> <component name="TodoView" selected-index="0"> <todo-panel id="selected-file"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="all"> <are-packages-shown value="true" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="default-changelist"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="false" /> </todo-panel> </component> <component name="ToolWindowManager"> - <frame x="-5" y="-3" width="2570" height="1509" extended-state="6" /> - <editor active="false" /> + <frame x="10" y="10" width="2540" height="1501" extended-state="0" /> + <editor active="true" /> <layout> - <window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Changes" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.23620309" sideWeight="0.0" order="7" side_tool="false" /> - <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> - <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" /> - <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4117647" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Clojure REPL" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.39411765" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" /> - <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.26274273" sideWeight="0.79096544" order="1" side_tool="false" /> - <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" /> - <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.16162421" sideWeight="0.7586461" order="0" side_tool="false" /> - <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" /> - <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.16703458" sideWeight="0.5" order="2" side_tool="false" /> - <window_info id="Regex Tester" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" /> - <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" /> - <window_info id="Atlassian " active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" /> - <window_info id="UML Diagrams" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="FindBugs-IDEA" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="JProfiler" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32941177" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Graphical Navigator" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.32988167" sideWeight="0.0" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> + <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.26274273" sideWeight="0.79096544" order="1" side_tool="false" content_ui="tabs" /> + <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> + <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.33293074" sideWeight="0.66494083" order="0" side_tool="false" content_ui="tabs" /> + <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23620309" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> + <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.41133186" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> + <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="Clojure REPL" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3119941" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Regex Tester" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> + <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> + <window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="Atlassian " active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> + <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> + <window_info id="UML Diagrams" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="FindBugs-IDEA" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="JProfiler" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32941177" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> + <window_info id="Graphical Navigator" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> + <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" /> </layout> </component> <component name="VcsManagerConfiguration"> <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" /> <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" /> <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" /> <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" /> + <option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" /> + <option name="CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND" value="true" /> <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> - <option name="LAST_COMMIT_MESSAGE" value="removing some &quot;global&quot; vars and making them more local in scope where&#10;possible. Cleaned up -main so that it is more clear what you have to do when&#10;calling it. &#10;&#10;Formatting and cleanup.&#10;&#10;Added a README." /> + <option name="LAST_COMMIT_MESSAGE" value="moved README out of src dir" /> + <option name="MAKE_NEW_CHANGELIST_ACTIVE" value="true" /> <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" /> + <option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" /> <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" /> <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" /> <option name="ACTIVE_VCS_NAME" /> <option name="UPDATE_GROUP_BY_PACKAGES" value="false" /> <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" /> <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" /> <MESSAGE value="update in IML appears to reference location of git binary" /> <MESSAGE value="starting to add a &quot;frames per second&quot; display, and now using the latest&#10;clojure snapshot to see if transients speed things up" /> <MESSAGE value="oops fixing size of cells" /> <MESSAGE value="removing some &quot;global&quot; vars and making them more local in scope where&#10;possible. Cleaned up -main so that it is more clear what you have to do when&#10;calling it. &#10;&#10;Formatting and cleanup.&#10;&#10;Added a README." /> + <MESSAGE value="updated IntelliJ project to use a more recent version of clojure that includes&#10;&quot;transients&quot;. The clojure jar I am using is checked in under the lib dir." /> + <MESSAGE value="formatting" /> + <MESSAGE value="wow fixing a major performance regression - when I moved the x-cells, y-cells,&#10;and cell-size to be locals that get passed around, performance took a nose&#10;dive. I am not sure why yet, but for now I will move them back out.&#10;&#10;I don't think cell-size needs to be moved out too, but I did so anyways since&#10;I was already moving out x-cells and y-cells.&#10;&#10;Also added one type hint in case it might help a tiny bit." /> + <MESSAGE value="docs, and typehint for perfomance&#10;&#10;looked at agent usage to see if I could keep the set of agents but no luck &#10;with the current model - maybe if the agents state was just @mycells,&#10;and when we send determine-new-state-in-agent we include the batch &#10;as a param. That might make a little more sense, and allow us to not create&#10;new agents for every iteration." /> + <MESSAGE value="typo" /> + <MESSAGE value="moved README out of src dir" /> </component> <component name="VssConfiguration"> <option name="CLIENT_PATH" value="" /> <option name="SRCSAFEINI_PATH" value="" /> <option name="USER_NAME" value="" /> <option name="PWD" value="" /> <CheckoutOptions> <option name="COMMENT" value="" /> <option name="DO_NOT_GET_LATEST_VERSION" value="false" /> <option name="REPLACE_WRITABLE" value="false" /> <option name="RECURSIVE" value="false" /> </CheckoutOptions> <CheckinOptions> <option name="COMMENT" value="" /> <option name="KEEP_CHECKED_OUT" value="false" /> <option name="RECURSIVE" value="false" /> </CheckinOptions> <AddOptions> <option name="STORE_ONLY_LATEST_VERSION" value="false" /> <option name="CHECK_OUT_IMMEDIATELY" value="false" /> </AddOptions> <UndocheckoutOptions> <option name="MAKE_WRITABLE" value="false" /> <option name="REPLACE_LOCAL_COPY" value="2" /> <option name="RECURSIVE" value="false" /> </UndocheckoutOptions> <GetOptions> <option name="REPLACE_WRITABLE" value="0" /> <option name="MAKE_WRITABLE" value="false" /> <option name="ANSWER_NEGATIVELY" value="false" /> <option name="ANSWER_POSITIVELY" value="false" /> <option name="RECURSIVE" value="false" /> <option name="VERSION" /> </GetOptions> </component> <component name="XDebuggerManager"> <breakpoint-manager /> </component> <component name="XPathView.XPathProjectComponent"> <history /> <find-history /> </component> <component name="antWorkspaceConfiguration"> <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> <option name="FILTER_TARGETS" value="false" /> </component> <component name="atlassian-ide-plugin-workspace"> <option name="bambooConfiguration"> <BambooWorkspaceConfiguration> <option name="view"> <BambooViewConfigurationBean /> </option> </BambooWorkspaceConfiguration> </option> <option name="crucibleConfiguration"> <CrucibleWorkspaceConfiguration> <option name="crucibleFilters"> <CrucibleFiltersBean> <option name="manualFilter"> <CustomFilterBean> <option name="serverUid" value="bc006778-5a48-43b5-94b8-8a55cbed9b35" /> </CustomFilterBean> </option> <option name="recenltyOpenFilter"> <RecentlyOpenReviewsFilter /> </option> </CrucibleFiltersBean> </option> <option name="view"> <CrucibleViewConfigurationBean /> </option> </CrucibleWorkspaceConfiguration> </option> <option name="defaultCredentials"> <UserCfgBean /> </option> </component> <component name="atlassian-ide-plugin-workspace-issues"> <option name="view"> <JiraViewConfigurationBean> <option name="viewFilterId" value="" /> <option name="viewServerId" value="" /> </JiraViewConfigurationBean> </option> </component> <component name="editorHistoryManager"> + <entry file="jar://$PROJECT_DIR$/lib/clojure-1.1.0-alpha-SNAPSHOT.jar!/clojure/core.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="-64.468124" /> + </provider> + </entry> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/clojure/core.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="1883" column="0" selection-start="62265" selection-end="62500" vertical-scroll-proportion="-13.04" /> + </provider> + </entry> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="234" column="22" selection-start="12863" selection-end="12863" vertical-scroll-proportion="1.0634615"> - <folding /> - </state> + <state line="253" column="0" selection-start="11888" selection-end="11888" vertical-scroll-proportion="1.2881137" /> </provider> </entry> - <entry file="file://$PROJECT_DIR$/src/README"> + <entry file="file://$PROJECT_DIR$/README"> <provider selected="true" editor-type-id="text-editor"> - <state line="19" column="10" selection-start="1202" selection-end="1202" vertical-scroll-proportion="0.67058825"> + <state line="22" column="131" selection-start="1244" selection-end="1244" vertical-scroll-proportion="0.37844038"> <folding /> </state> </provider> </entry> </component> <component name="masterDetails"> - <option name="states"> - <map> - <entry key="Copyright.UI"> - <value> - <UIState> + <states> + <state key="ArtifactsStructureConfigurable.UI"> + <UIState> + <splitter-proportions> + <SplitterProportionsDataImpl> <option name="proportions"> - <SplitterProportionsDataImpl /> + <list> + <option value="0.2" /> + </list> </option> - </UIState> - </value> - </entry> - <entry key="Errors.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl /> - </option> - </UIState> - </value> - </entry> - <entry key="ProjectJDKs.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl> - <option name="proportions"> - <list> - <option value="0.2" /> - </list> - </option> - </SplitterProportionsDataImpl> - </option> - </UIState> - </value> - </entry> - <entry key="ScopeChooserConfigurable.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl /> - </option> - </UIState> - </value> - </entry> - </map> - </option> - <option name="myStates"> - <map> - <entry key="Copyright.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl /> - </option> - </UIState> - </value> - </entry> - <entry key="Errors.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl /> - </option> - </UIState> - </value> - </entry> - <entry key="ProjectJDKs.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl> - <option name="proportions"> - <list> - <option value="0.2" /> - </list> - </option> - </SplitterProportionsDataImpl> - </option> - </UIState> - </value> - </entry> - <entry key="ScopeChooserConfigurable.UI"> - <value> - <UIState> - <option name="proportions"> - <SplitterProportionsDataImpl /> - </option> - </UIState> - </value> - </entry> - </map> - </option> + </SplitterProportionsDataImpl> + </splitter-proportions> + <settings /> + </UIState> + </state> + <state key="ScopeChooserConfigurable.UI"> + <UIState> + <splitter-proportions> + <SplitterProportionsDataImpl /> + </splitter-proportions> + <settings /> + </UIState> + </state> + </states> </component> </project> diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 1d78e09..a076742 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,252 +1,254 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 2)) (def y-cells ( * 48 2)) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) ;(set! *warn-on-reflection* true) ; @param arg-num-threads How many windows to open ; @param x-cells, y-cells Dimensions of the grid - make this bigger if you have more horsepower! ; @param cell-size Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (defn -main [arg-num-threads] ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads arg-num-threads) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] [; the Panels have a custom paint function that first calls paint-cells then paints some stats on the window (proxy [JPanel] [] (paint [#^java.awt.Graphics graphics] ; paint the grid of cells (paint-cells graphics cell-state) ; increment our total frames painted (let [totalframes (swap! frames inc) ts (System/currentTimeMillis)] ; now overlay a little info about frames per second and total frames drawn ; draw into the upper left of the window how many frames painted so far, and the rough "frames per second" (doto graphics (.setColor Color/WHITE) (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) ; reset lastts, lastfps, and lastframes if we just rolled over (if (> ts (+ @lastts 1000)) (do (reset! lastts ts) (reset! lastfps (- @frames @lastframes)) (reset! lastframes @frames)))))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5)) ) (when 1 (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads"))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5))) (when 1 (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; figures out what the next state for a given cell should be (defn determine-new-state [x y mycells] ; figure out how many cells around us are alive (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) ; note how we use modulus here to get cells to "overlap" edge of grid (not (= empty-color (mycells [(mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells)))) ; This is the all important function where parallelization kicks in ; I find it confusing how I am using agents here - the initial state is batch-sets, but the output is a going to mycells ; would be nice to have agents that I don't have to recreate for every pass (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) ; now copy all the results from the agents into @mycells so that we can paint the results to the panel (dosync (ref-set mycells + ; I am going to guess we spend a ton of time here + ; the new transient based into might be helping us here, but swapping it in/out didn't help as much as I hoped (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [#^java.awt.Panel panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ; agents (map #(agent %) batch-set) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) (if @running (recur)))) start))))) (let [num-windows 3 ;x-cells (* 32 3) ;y-cells (* 48 3) ;cell-size 5] ] (-main num-windows))
sfraser/MultithreadedGameOfLife
386cdf6da6f4297257e4533778526e380769e20a
docs, and typehint for perfomance looked at agent usage to see if I could keep the set of agents but no luck with the current model - maybe if the agents state was just @mycells, and when we send determine-new-state-in-agent we include the batch as a param. That might make a little more sense, and allow us to not create new agents for every iteration.
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 6a82a30..1d78e09 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,246 +1,252 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 2)) (def y-cells ( * 48 2)) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) +;(set! *warn-on-reflection* true) + ; @param arg-num-threads How many windows to open ; @param x-cells, y-cells Dimensions of the grid - make this bigger if you have more horsepower! ; @param cell-size Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (defn -main [arg-num-threads] ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads arg-num-threads) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] [; the Panels have a custom paint function that first calls paint-cells then paints some stats on the window (proxy [JPanel] [] (paint [#^java.awt.Graphics graphics] ; paint the grid of cells (paint-cells graphics cell-state) ; increment our total frames painted - - ; now overlay a little info about frames per second and total frames drawn (let [totalframes (swap! frames inc) ts (System/currentTimeMillis)] + ; now overlay a little info about frames per second and total frames drawn ; draw into the upper left of the window how many frames painted so far, and the rough "frames per second" (doto graphics (.setColor Color/WHITE) (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) ; reset lastts, lastfps, and lastframes if we just rolled over (if (> ts (+ @lastts 1000)) (do (reset! lastts ts) (reset! lastfps (- @frames @lastframes)) (reset! lastframes @frames)))))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5)) ) (when 1 (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads"))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5))) (when 1 (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) +; figures out what the next state for a given cell should be (defn determine-new-state [x y mycells] + ; figure out how many cells around us are alive (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) - (not (= empty-color - (mycells - [(mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] + ; note how we use modulus here to get cells to "overlap" edge of grid + (not (= empty-color (mycells [(mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] - ;first here is the vector of [x y], and second is the state (color) - [[(first %) (second %)] new-cell-state]) - batch-cells)))) + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells)))) ; This is the all important function where parallelization kicks in +; I find it confusing how I am using agents here - the initial state is batch-sets, but the output is a going to mycells +; would be nice to have agents that I don't have to recreate for every pass (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) + ; now copy all the results from the agents into @mycells so that we can paint the results to the panel (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button -(defn toggle-thread [panel mycells batch-set] +(defn toggle-thread [#^java.awt.Panel panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) - (ref-set mycounter 0) - (alter mycounter inc))) + (ref-set mycounter 0) + (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) + ; agents (map #(agent %) batch-set) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) (if @running (recur)))) start))))) (let [num-windows 3 ;x-cells (* 32 3) ;y-cells (* 48 3) ;cell-size 5] ] (-main num-windows))
sfraser/MultithreadedGameOfLife
179f526ca2458f04051a3aeb1f27132ff785f3cf
wow fixing a major performance regression - when I moved the x-cells, y-cells, and cell-size to be locals that get passed around, performance took a nose dive. I am not sure why yet, but for now I will move them back out. I don't think cell-size needs to be moved out too, but I did so anyways since I was already moving out x-cells and y-cells. Also added one type hint in case it might help a tiny bit.
diff --git a/src/README b/src/README index 5caf562..f637288 100644 --- a/src/README +++ b/src/README @@ -1,31 +1,33 @@ This program runs 1 to many Game of Life simulations. For more on the "Game of Life", see: http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life This code uses clojure concurrency primitives to demonstrate how threads can be used to get more done in less time. The more cores you have, the more effective a demonstration. Each window this program opens has it's own set of threads to execute the simulation. By watching a window with 1 thread versus a window with 2, 3, or 4, you will visually see the power of parallelizing CPU intensive work. At the start of the simultion each window starts out with the same "state". When you hit the Start button (on any window), all the windows will start running the Game of Life. Each thread will use a specific color so that you can visually see the parallelism of the process. The windows are assigned an increasing number of threads from 1 to the total number of windows opened. So if you ask for 3 windows, you will get one window with 1 thread, another with 2 threads, and a third with 3. There is a "total frames" and a "frames per second" indicator on each window so you can also get a rough feel for how fast each window is running. How to Run -Call -main with the following params: +At the top of the file set these vars: -* number of windows you want to see -* how many rows of cells on the x-axis -* how many rows of cells on the y-axis -* how large the cells should be +; Dimensions of the grid - make this bigger if you have more horsepower! +(def x-cells ( * 32 2)) +(def y-cells ( * 48 2)) + +; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids +(def cell-size 5) -For example, to see 3 windows, that are 60x100 with cells 10 pixels in size: +Then call -main with the following params: -(-main 3 60 100 10) \ No newline at end of file +* number of windows you want to see
sfraser/MultithreadedGameOfLife
03c3621c262d2828a71ffb511a8c9b4f04617320
wow fixing a major performance regression - when I moved the x-cells, y-cells, and cell-size to be locals that get passed around, performance took a nose dive. I am not sure why yet, but for now I will move them back out. I don't think cell-size needs to be moved out too, but I did so anyways since I was already moving out x-cells and y-cells. Also added one type hint in case it might help a tiny bit.
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 6089132..6a82a30 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,238 +1,246 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) +; Dimensions of the grid - make this bigger if you have more horsepower! +(def x-cells ( * 32 2)) +(def y-cells ( * 48 2)) + +; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids +(def cell-size 5) + ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) ; @param arg-num-threads How many windows to open ; @param x-cells, y-cells Dimensions of the grid - make this bigger if you have more horsepower! ; @param cell-size Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids -(defn -main [arg-num-threads x-cells y-cells cell-size] +(defn -main [arg-num-threads] ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads arg-num-threads) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] [; the Panels have a custom paint function that first calls paint-cells then paints some stats on the window - (proxy [JPanel] [] (paint [graphics] + (proxy [JPanel] [] (paint [#^java.awt.Graphics graphics] ; paint the grid of cells - (paint-cells graphics cell-state cell-size) + (paint-cells graphics cell-state) ; increment our total frames painted ; now overlay a little info about frames per second and total frames drawn (let [totalframes (swap! frames inc) ts (System/currentTimeMillis)] ; draw into the upper left of the window how many frames painted so far, and the rough "frames per second" (doto graphics (.setColor Color/WHITE) (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) ; reset lastts, lastfps, and lastframes if we just rolled over (if (> ts (+ @lastts 1000)) (do (reset! lastts ts) (reset! lastfps (- @frames @lastframes)) (reset! lastframes @frames)))))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5)) ) (when 1 (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads"))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5))) (when 1 - (toggle-thread panel cell-state batch-set x-cells y-cells))))))))) + (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) -(defn determine-new-state [x y mycells x-cells y-cells] +(defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [(mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes -(defn determine-new-state-in-agent [batch-cells mycells next-color-fn x-cells y-cells] +(defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] - (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells x-cells y-cells) thread-color empty-color)] + (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells)))) ; This is the all important function where parallelization kicks in -(defn calc-state-with-agents [batch-set mycells next-color-fn x-cells y-cells] +(defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] - (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn x-cells y-cells)))) + (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better -(defn paint-cells [#^java.awt.Graphics graphics mycells cell-size] +(defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button -(defn toggle-thread [panel mycells batch-set x-cells y-cells] +(defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) - (calc-state-with-agents batch-set mycells next-color-fn x-cells y-cells) + (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) (if @running (recur)))) start))))) (let [num-windows 3 - x-cells (* 32 3) - y-cells (* 48 3) - cell-size 5] - (-main num-windows x-cells y-cells cell-size)) + ;x-cells (* 32 3) + ;y-cells (* 48 3) + ;cell-size 5] + ] + (-main num-windows))
sfraser/MultithreadedGameOfLife
97980b04fddacb3eb16e424d58a55856dd3e11fa
formatting
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 08559ba..6089132 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,238 +1,238 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) - '(java.awt BorderLayout Dimension Color) - '(java.awt.event ActionListener)) + '(java.awt BorderLayout Dimension Color) + '(java.awt.event ActionListener)) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) ; @param arg-num-threads How many windows to open ; @param x-cells, y-cells Dimensions of the grid - make this bigger if you have more horsepower! ; @param cell-size Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids -(defn -main[arg-num-threads x-cells y-cells cell-size] +(defn -main [arg-num-threads x-cells y-cells cell-size] - ; sequence of all the valid coordinates - (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) + ; sequence of all the valid coordinates + (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) - ; Example of setting number of threads based on the number of processors the JVM can see - ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) + ; Example of setting number of threads based on the number of processors the JVM can see + ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads arg-num-threads) - ; First we need to calculate the initial state that all the windows will start with - ; easiest way is to have one map of cell states that all windows initially point to - ; so we create an initial-state ref - ; and then set up a list of vectors: [threadNumber initialState] + ; First we need to calculate the initial state that all the windows will start with + ; easiest way is to have one map of cell states that all windows initially point to + ; so we create an initial-state ref + ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs - (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) - ] - - ; this is where we calculate the initial state of the first window - ; since all windows are initially pointing at the same map, everyone will - ; start up with the same state - ; Would be nice to clean this up so at starup each window actually had the same number of colors it - ; will have after the user hits "start" + (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) + ] + + ; this is where we calculate the initial state of the first window + ; since all windows are initially pointing at the same map, everyone will + ; start up with the same state + ; Would be nice to clean this up so at starup each window actually had the same number of colors it + ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) - ; make a list of vectors of [panel procs cell-state precalced-batch-sets] - ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different - ; sized for each window + ; make a list of vectors of [panel procs cell-state precalced-batch-sets] + ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different + ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] - [ ; the Panels have a custom paint function that first calls paint-cells then paints some stats on the window - (proxy [JPanel] [] (paint [graphics] - ; paint the grid of cells - (paint-cells graphics cell-state cell-size) - ; increment our total frames painted - - ; now overlay a little info about frames per second and total frames drawn - (let [totalframes (swap! frames inc) - ts (System/currentTimeMillis)] - ; draw into the upper left of the window how many frames painted so far, and the rough "frames per second" - (doto graphics - (.setColor Color/WHITE) - (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) - ; reset lastts, lastfps, and lastframes if we just rolled over - (if (> ts (+ @lastts 1000)) - (do - (reset! lastts ts) - (reset! lastfps (- @frames @lastframes)) - (reset! lastframes @frames)))))) - threadNumber - cell-state - ; since each window has a different set of threads, we calculate a "batch set" sized right for this window - ; so for the 1 thread window there will be one big batch with all cells listed - ; for a 2 thread window we will have 2 sets of cells listed - (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) - ]))) - - - ; Used across all threads to signal if we are running or not - ; Toggled by the Start/Stop buttons + [; the Panels have a custom paint function that first calls paint-cells then paints some stats on the window + (proxy [JPanel] [] (paint [graphics] + ; paint the grid of cells + (paint-cells graphics cell-state cell-size) + ; increment our total frames painted + + ; now overlay a little info about frames per second and total frames drawn + (let [totalframes (swap! frames inc) + ts (System/currentTimeMillis)] + ; draw into the upper left of the window how many frames painted so far, and the rough "frames per second" + (doto graphics + (.setColor Color/WHITE) + (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) + ; reset lastts, lastfps, and lastframes if we just rolled over + (if (> ts (+ @lastts 1000)) + (do + (reset! lastts ts) + (reset! lastfps (- @frames @lastframes)) + (reset! lastframes @frames)))))) + threadNumber + cell-state + ; since each window has a different set of threads, we calculate a "batch set" sized right for this window + ; so for the 1 thread window there will be one big batch with all cells listed + ; for a 2 thread window we will have 2 sets of cells listed + (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) + ]))) + + + ; Used across all threads to signal if we are running or not + ; Toggled by the Start/Stop buttons (def running (atom false)) - ; now we loop through the panels-and-state and materialize each one as a Swing JFrame - ; @param panel JPanel with a threadNumber and current set of cell-state - ; @param procs number of processes to use for this panel - ; @param cell-state current cell-state for this panel - ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel + ; now we loop through the panels-and-state and materialize each one as a Swing JFrame + ; @param panel JPanel with a threadNumber and current set of cell-state + ; @param procs number of processes to use for this panel + ; @param cell-state current cell-state for this panel + ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] - ; todo - this is a horrible kludge to just show 4 versus 1 thread + ; todo - this is a horrible kludge to just show 4 versus 1 thread ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5)) ) (when 1 - (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) + (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads"))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener - (proxy [ActionListener] [] - (actionPerformed [evt] - (reset! running (false? @running)) - (. b (setText (if @running "Start" "Stop"))) - (doseq [[panel procs cell-state batch-set] panels-and-state] - ; @todo - this is a horrible kludge to just show 4 versus 1 thread - ;(when (and (not (= procs 3)) (not (= procs 5))) - (when 1 - (toggle-thread panel cell-state batch-set x-cells y-cells))))))))) + (proxy [ActionListener] [] + (actionPerformed [evt] + (reset! running (false? @running)) + (. b (setText (if @running "Start" "Stop"))) + (doseq [[panel procs cell-state batch-set] panels-and-state] + ; @todo - this is a horrible kludge to just show 4 versus 1 thread + ;(when (and (not (= procs 3)) (not (= procs 5))) + (when 1 + (toggle-thread panel cell-state batch-set x-cells y-cells))))))))) ) (defn next-color [] - (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) - (ref-set counter 0) - (alter counter inc)))) + (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) + (ref-set counter 0) + (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) (defn determine-new-state [x y mycells x-cells y-cells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) - (not (= empty-color - (mycells - [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] - :alive))] + (not (= empty-color + (mycells + [(mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] + :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) - ; replaced this with a single threaded reduce in calc-state - ; DEPRECATED - need to eliminate this, it is only used in startup now +; replaced this with a single threaded reduce in calc-state +; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync - ; first here is the vector of [x y], and second is the state - (dorun (map #(commute new-cells assoc (first %) (second %)) - list-of-batches)))) + ; first here is the vector of [x y], and second is the state + (dorun (map #(commute new-cells assoc (first %) (second %)) + list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] - ( let [thread-color (nth color-list (next-color-fn))] + (let [thread-color (nth color-list (next-color-fn))] doall (map - #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] - ;first here is the vector of [x y], and second is the state (color) - [[(first %) (second %)] new-cell-state]) - batch-cells))) + #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells))) - ; This is the all important function where parallelization kicks in - ; DEPRECATED - need to eliminate this, it is only used in startup now +; This is the all important function where parallelization kicks in +; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) - (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) - batch-set))) + (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) + batch-set))) (dosync (ref-set mycells @new-cells)))) - ; this function is passed into an agent - ; the agent will map it onto its batch-set, updating the batch-set as it goes +; this function is passed into an agent +; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn x-cells y-cells] (let [thread-color (nth color-list (next-color-fn))] (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells x-cells y-cells) thread-color empty-color)] - ;first here is the vector of [x y], and second is the state (color) - [[(first %) (second %)] new-cell-state]) - batch-cells)))) + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells)))) - ; This is the all important function where parallelization kicks in +; This is the all important function where parallelization kicks in (defn calc-state-with-agents [batch-set mycells next-color-fn x-cells y-cells] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn x-cells y-cells)))) (apply await agents) (dosync (ref-set mycells - (reduce into {} - (map deref agents)))))) + (reduce into {} + (map deref agents)))))) - ; Type Hint here makes a huge performance difference for the better +; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells cell-size] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) - ; This is what gets called when you hit the State/Stop button +; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set x-cells y-cells] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) - (ref-set mycounter 0) - (alter mycounter inc))) - ; set of agents for this windows exclusive use for painting - there will be one agent per batch set - ; assert (count (batch-set) == procs) - ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) - ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] - ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) + (ref-set mycounter 0) + (alter mycounter inc))) + ; set of agents for this windows exclusive use for painting - there will be one agent per batch set + ; assert (count (batch-set) == procs) + ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) + ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] + ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. - #(loop [] - ;(calc-state determine-new-state mycells batch-set next-color) - (calc-state-with-agents batch-set mycells next-color-fn x-cells y-cells) - (.repaint panel) - (if @running (recur)))) - start))))) + #(loop [] + ;(calc-state determine-new-state mycells batch-set next-color) + (calc-state-with-agents batch-set mycells next-color-fn x-cells y-cells) + (.repaint panel) + (if @running (recur)))) + start))))) (let [num-windows 3 - x-cells ( * 32 3) - y-cells ( * 48 3) + x-cells (* 32 3) + y-cells (* 48 3) cell-size 5] (-main num-windows x-cells y-cells cell-size))
sfraser/MultithreadedGameOfLife
0acaa0711e6b67ee1f6b68944cbd5b2cb77e7f2c
removing some "global" vars and making them more local in scope where possible. Cleaned up -main so that it is more clear what you have to do when calling it. Formatting and cleanup. Added a README.
diff --git a/src/README b/src/README new file mode 100644 index 0000000..5caf562 --- /dev/null +++ b/src/README @@ -0,0 +1,31 @@ + +This program runs 1 to many Game of Life simulations. For more on the "Game of Life", see: + http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life + +This code uses clojure concurrency primitives to demonstrate how threads can be used to get more done in less time. +The more cores you have, the more effective a demonstration. + +Each window this program opens has it's own set of threads to execute the simulation. By watching a window with 1 +thread versus a window with 2, 3, or 4, you will visually see the power of parallelizing CPU intensive work. + +At the start of the simultion each window starts out with the same "state". When you hit the Start button (on any +window), all the windows will start running the Game of Life. Each thread will use a specific color so that you can +visually see the parallelism of the process. The windows are assigned an increasing number of threads from 1 to the +total number of windows opened. So if you ask for 3 windows, you will get one window with 1 thread, another with 2 +threads, and a third with 3. + +There is a "total frames" and a "frames per second" indicator on each window so you can also get a rough feel for how +fast each window is running. + +How to Run + +Call -main with the following params: + +* number of windows you want to see +* how many rows of cells on the x-axis +* how many rows of cells on the y-axis +* how large the cells should be + +For example, to see 3 windows, that are 60x100 with cells 10 pixels in size: + +(-main 3 60 100 10) \ No newline at end of file diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index a628271..08559ba 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,241 +1,238 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) -; Used across all threads to signal if we are running or not -; Toggled by the Start/Stop buttons -(def running (atom false)) - -; Dimensions of the grid - make this bigger if you have more horsepower! -(def x-cells ( * 32 2)) -(def y-cells ( * 48 2)) -;(def x-cells 32) -;(def y-cells 32) - -; sequence of all the valid coordinates -(def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) - - -; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids -(def cell-size 5 ) -; Optional Thread sleep factor to slow simulation down - I usually don't use it -(def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) -(defn -main[arg-num-threads] +; @param arg-num-threads How many windows to open +; @param x-cells, y-cells Dimensions of the grid - make this bigger if you have more horsepower! +; @param cell-size Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids +(defn -main[arg-num-threads x-cells y-cells cell-size] + + ; sequence of all the valid coordinates + (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) - (def num-threads (Integer/parseInt arg-num-threads)) + (def num-threads arg-num-threads) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] - [(proxy [JPanel] [] (paint [graphics] - ; paint the grid of cells - (paint-cells graphics cell-state) - ; increment our total frames painted - - ; now overlay a little info about frames per second and total frames drawn - ; figure out if we passed over 1 second since last mark - (let [totalframes (swap! frames inc) - ts (System/currentTimeMillis)] - ; fps (if secondpassed (reset! fps (- @frames @lastmark))) - (doto graphics - (.setColor Color/WHITE) - (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) - ; reset lastts, lastfps, and lastframes if we just rolled over - (if (> ts (+ @lastts 1000)) - (do - (reset! lastts ts) - (reset! lastfps (- @frames @lastframes)) - (reset! lastframes @frames)))))) - threadNumber - cell-state - ; since each window has a different set of threads, we calculate a "batch set" sized right for this window - ; so for the 1 thread window there will be one big batch with all cells listed - ; for a 2 thread window we will have 2 sets of cells listed - (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) - ]))) - - ; now we loop through the panels-and-state and materialize each one as a Swing JFrame + [ ; the Panels have a custom paint function that first calls paint-cells then paints some stats on the window + (proxy [JPanel] [] (paint [graphics] + ; paint the grid of cells + (paint-cells graphics cell-state cell-size) + ; increment our total frames painted + + ; now overlay a little info about frames per second and total frames drawn + (let [totalframes (swap! frames inc) + ts (System/currentTimeMillis)] + ; draw into the upper left of the window how many frames painted so far, and the rough "frames per second" + (doto graphics + (.setColor Color/WHITE) + (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) + ; reset lastts, lastfps, and lastframes if we just rolled over + (if (> ts (+ @lastts 1000)) + (do + (reset! lastts ts) + (reset! lastfps (- @frames @lastframes)) + (reset! lastframes @frames)))))) + threadNumber + cell-state + ; since each window has a different set of threads, we calculate a "batch set" sized right for this window + ; so for the 1 thread window there will be one big batch with all cells listed + ; for a 2 thread window we will have 2 sets of cells listed + (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) + ]))) + + + ; Used across all threads to signal if we are running or not + ; Toggled by the Start/Stop buttons + (def running (atom false)) + + ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread + ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5)) ) (when 1 (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] - ; todo - this is a horrible kludge to just show 4 versus 1 thread + ; @todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5))) (when 1 - (toggle-thread panel cell-state batch-set))))))))) + (toggle-thread panel cell-state batch-set x-cells y-cells))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) -(defn determine-new-state [x y mycells] +(defn determine-new-state [x y mycells x-cells y-cells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] ( let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes -(defn determine-new-state-in-agent [batch-cells mycells next-color-fn] +(defn determine-new-state-in-agent [batch-cells mycells next-color-fn x-cells y-cells] (let [thread-color (nth color-list (next-color-fn))] - (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] + (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells x-cells y-cells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells)))) ; This is the all important function where parallelization kicks in -(defn calc-state-with-agents [batch-set mycells next-color-fn] +(defn calc-state-with-agents [batch-set mycells next-color-fn x-cells y-cells] (let [agents (map #(agent %) batch-set)] (doseq [a agents] - (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) + (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn x-cells y-cells)))) (apply await agents) (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better -(defn paint-cells [#^java.awt.Graphics graphics mycells] +(defn paint-cells [#^java.awt.Graphics graphics mycells cell-size] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button -(defn toggle-thread [panel mycells batch-set] +(defn toggle-thread [panel mycells batch-set x-cells y-cells] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) - (calc-state-with-agents batch-set mycells next-color-fn) + (calc-state-with-agents batch-set mycells next-color-fn x-cells y-cells) (.repaint panel) - ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) +(let [num-windows 3 + x-cells ( * 32 3) + y-cells ( * 48 3) + cell-size 5] + (-main num-windows x-cells y-cells cell-size)) -(-main "3")
sfraser/MultithreadedGameOfLife
158c346d7c418571a94bf8f3869d5d6a5fc7705e
oops fixing size of cells
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 83ae4eb..a628271 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,241 +1,241 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 2)) (def y-cells ( * 48 2)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids -(def cell-size 1 ) +(def cell-size 5 ) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] [(proxy [JPanel] [] (paint [graphics] ; paint the grid of cells (paint-cells graphics cell-state) ; increment our total frames painted ; now overlay a little info about frames per second and total frames drawn ; figure out if we passed over 1 second since last mark (let [totalframes (swap! frames inc) ts (System/currentTimeMillis)] ; fps (if secondpassed (reset! fps (- @frames @lastmark))) (doto graphics (.setColor Color/WHITE) (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) ; reset lastts, lastfps, and lastframes if we just rolled over (if (> ts (+ @lastts 1000)) (do (reset! lastts ts) (reset! lastfps (- @frames @lastframes)) (reset! lastframes @frames)))))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5)) ) (when 1 (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread ;(when (and (not (= procs 3)) (not (= procs 5))) (when 1 (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] ( let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells)))) ; This is the all important function where parallelization kicks in (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
380ec8a6d32911dcd9f39ac02c1c4abcbf43580e
got the fps indicator working - however note I think I can just used closed over refs instead of atoms
diff --git a/MultithreadedGameOfLife.iws b/MultithreadedGameOfLife.iws index f0ae884..960ba9a 100644 --- a/MultithreadedGameOfLife.iws +++ b/MultithreadedGameOfLife.iws @@ -1,593 +1,596 @@ <?xml version="1.0" encoding="UTF-8"?> <project relativePaths="false" version="4"> - <component name="BookmarkManager"> - <editor_bookmark url="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" line="85" number="1" description="(doto graphics (.setColor Color/WHITE) (.drawStrin..." /> - </component> <component name="CCaseConfig"> <option name="checkoutReserved" value="false" /> <option name="markExternalChangeAsUpToDate" value="true" /> <option name="checkInUseHijack" value="true" /> <option name="useUcmModel" value="true" /> <option name="isOffline" value="false" /> <option name="synchOutside" value="false" /> <option name="isHistoryResticted" value="true" /> <option name="useIdenticalSwitch" value="true" /> <option name="synchActivitiesOnRefresh" value="true" /> <option name="lastScr" value="" /> <option name="scrTextFileName" value="" /> <option name="historyRevisionsNumber" value="4" /> </component> <component name="ChangeListManager"> <list default="true" name="Default" comment=""> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" afterPath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/lib/clojure-1.1.0-alpha-SNAPSHOT.jar" /> </list> <ignored path="MultithreadedGameOfLife.iws" /> <ignored path=".idea/workspace.xml" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="Commander"> <leftPanel /> <rightPanel /> <splitter proportion="0.5" /> </component> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> <option name="REVERSE_PATCH" value="false" /> </component> <component name="DaemonCodeAnalyzer"> <disable_hints /> </component> <component name="DebuggerManager"> <breakpoint_any> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> </breakpoint_any> <breakpoint_rules /> <ui_properties /> </component> <component name="FavoritesManager"> <favorites_list name="MultithreadedGameOfLife" /> </component> <component name="FileEditorManager"> <leaf> <file leaf-file-name="MultiThreadedLife.clj" pinned="false" current="true" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="85" column="117" selection-start="4306" selection-end="4306" vertical-scroll-proportion="0.2516704"> + <state line="91" column="10" selection-start="4436" selection-end="4436" vertical-scroll-proportion="0.5201794"> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="false" /> </FindUsagesManager> </component> <component name="Git.Settings"> <option name="GIT_EXECUTABLE" value="/usr/local/git/bin/git" /> </component> <component name="ModuleEditorState"> <option name="LAST_EDITED_MODULE_NAME" /> <option name="LAST_EDITED_TAB_NAME" /> </component> <component name="ProjectLevelVcsManager"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <OptionsSetting value="true" id="Undo Check Out" /> <OptionsSetting value="true" id="Get Latest Version" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> </PATH> </subPane> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <showStructure ProjectPane="false" /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> </component> <component name="PropertiesComponent"> <property name="project.structure.proportion" value="0.15" /> <property name="MemberChooser.copyJavadoc" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder2" value="2" /> <property name="options.splitter.main.proportions" value="0.3" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder2" value="2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="893" /> <property name="GoToFile.includeJavaFiles" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="82" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="99" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="103" /> <property name="GoToClass.includeLibraries" value="false" /> <property name="options.splitter.details.proportions" value="0.2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder3" value="3" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder0" value="0" /> <property name="MemberChooser.showClasses" value="true" /> <property name="project.structure.side.proportion" value="0.2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="94" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder3" value="3" /> <property name="options.lastSelected" value="preferences.pluginManager" /> <property name="GoToClass.toSaveIncludeLibraries" value="false" /> <property name="RunManagerConfig.showSettingsBeforeRunnig" value="true" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder0" value="0" /> <property name="project.structure.last.edited" value="Modules" /> <property name="options.searchVisible" value="true" /> <property name="MemberChooser.sorted" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder1" value="1" /> <property name="last_opened_file_path" value="/home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="115" /> <property name="dynamic.classpath" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="897" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="119" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder1" value="1" /> </component> <component name="RegexUtilComponent" text="1900-01-01 2007/08/13 1900.01.01 1900 01 01 1900-01.01 1900 13 01 1900 02 31" mode="0" flags="0" regex="(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])" /> <component name="RunManager" selected="Clojure Script.MultiThreadedLife"> <configuration default="true" type="Remote" factoryName="Remote"> <option name="USE_SOCKET_TRANSPORT" value="true" /> <option name="SERVER_MODE" value="false" /> <option name="SHMEM_ADDRESS" value="javadebug" /> <option name="HOST" value="localhost" /> <option name="PORT" value="5005" /> </configuration> <configuration default="true" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="" /> <setting name="path" value="" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="" /> <setting name="repl" value="false" /> </configuration> <configuration default="true" type="Applet" factoryName="Applet"> <module name="" /> <option name="MAIN_CLASS_NAME" /> <option name="HTML_FILE_NAME" /> <option name="HTML_USED" value="false" /> <option name="WIDTH" value="400" /> <option name="HEIGHT" value="300" /> <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" /> <option name="VM_PARAMETERS" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> </configuration> <configuration default="true" type="JUnit" factoryName="JUnit" enabled="false" merge="false" runner="emma"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="TEST_OBJECT" value="class" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <envs /> </configuration> <configuration default="true" type="Application" factoryName="Application" enabled="false" merge="false" runner="emma"> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> </configuration> <configuration default="false" name="MultiThreadedLife" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="MultithreadedGameOfLife" /> <setting name="path" value="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="$PROJECT_DIR$/src/org/frasers/life" /> <setting name="repl" value="false" /> <RunnerSettings RunnerId="JProfiler"> <option name="WINDOW" value="false" /> <option name="JVMPI" value="false" /> <option name="INTERPRETED" value="false" /> </RunnerSettings> <RunnerSettings RunnerId="Run" /> <ConfigurationWrapper RunnerId="JProfiler" /> <ConfigurationWrapper RunnerId="Run" /> <method> <option name="Make" value="true" /> </method> </configuration> <list size="1"> <item index="0" class="java.lang.String" itemvalue="Clojure Script.MultiThreadedLife" /> </list> <configuration default="true" type="TestNG" factoryName="TestNG" enabled="false" merge="false" runner="emma"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="SUITE_NAME" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="GROUP_NAME" /> <option name="TEST_OBJECT" value="CLASS" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="OUTPUT_DIRECTORY" /> <option name="ANNOTATION_TYPE" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <option name="PROPERTIES_FILE" /> <envs /> <properties /> <listeners /> </configuration> <configuration name="&lt;template&gt;" type="WebApp" default="true" selected="false"> <Host>localhost</Host> <Port>5050</Port> </configuration> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="StarteamConfiguration"> <option name="SERVER" value="" /> <option name="PORT" value="49201" /> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="PROJECT" value="" /> <option name="VIEW" value="" /> <option name="ALTERNATIVE_WORKING_PATH" value="" /> <option name="LOCK_ON_CHECKOUT" value="false" /> <option name="UNLOCK_ON_CHECKIN" value="false" /> </component> <component name="StructureViewFactory"> <option name="AUTOSCROLL_MODE" value="true" /> <option name="AUTOSCROLL_FROM_SOURCE" value="false" /> - <option name="ACTIVE_ACTIONS" value="" /> + <option name="ACTIVE_ACTIONS" value="ALPHA_COMPARATOR" /> </component> <component name="SvnConfiguration"> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="LAST_MERGED_REVISION" /> <option name="UPDATE_RUN_STATUS" value="false" /> <option name="MERGE_DRY_RUN" value="false" /> <option name="MERGE_DIFF_USE_ANCESTRY" value="true" /> <option name="UPDATE_LOCK_ON_DEMAND" value="false" /> <option name="IGNORE_SPACES_IN_MERGE" value="false" /> <configuration useDefault="true">/home/sfraser/.subversion</configuration> <myIsUseDefaultProxy>false</myIsUseDefaultProxy> </component> <component name="TodoView" selected-index="0"> <todo-panel id="selected-file"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="all"> <are-packages-shown value="true" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="default-changelist"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="false" /> </todo-panel> </component> <component name="ToolWindowManager"> <frame x="0" y="22" width="1280" height="774" extended-state="0" /> <editor active="false" /> <layout> <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Graphical Navigator" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Clojure REPL" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23235294" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Clojure REPL" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.39411765" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" /> <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.24675325" sideWeight="0.64506173" order="0" side_tool="false" /> - <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.26298702" sideWeight="0.7617647" order="1" side_tool="false" /> + <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.26298702" sideWeight="0.71911764" order="1" side_tool="false" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" /> <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" /> <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="UML Diagrams" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="FindBugs-IDEA" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Regex Tester" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.2367647" sideWeight="0.0" order="7" side_tool="false" /> - <window_info id="Run" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.22794117" sideWeight="0.5" order="2" side_tool="false" /> + <window_info id="Run" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.27058825" sideWeight="0.5" order="2" side_tool="false" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="JProfiler" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32941177" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4117647" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> <window_info id="Atlassian " active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" /> <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> </layout> </component> <component name="VcsManagerConfiguration"> <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" /> <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" /> <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" /> <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" /> <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> - <option name="LAST_COMMIT_MESSAGE" value="update in IML appears to reference location of git binary" /> + <option name="LAST_COMMIT_MESSAGE" value="starting to add a &quot;frames per second&quot; display, and now using the latest&#10;clojure snapshot to see if transients speed things up" /> <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" /> <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" /> <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" /> <option name="ACTIVE_VCS_NAME" /> <option name="UPDATE_GROUP_BY_PACKAGES" value="false" /> <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" /> <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" /> <MESSAGE value="update in IML appears to reference location of git binary" /> + <MESSAGE value="starting to add a &quot;frames per second&quot; display, and now using the latest&#10;clojure snapshot to see if transients speed things up" /> </component> <component name="VssConfiguration"> <option name="CLIENT_PATH" value="" /> <option name="SRCSAFEINI_PATH" value="" /> <option name="USER_NAME" value="" /> <option name="PWD" value="" /> <CheckoutOptions> <option name="COMMENT" value="" /> <option name="DO_NOT_GET_LATEST_VERSION" value="false" /> <option name="REPLACE_WRITABLE" value="false" /> <option name="RECURSIVE" value="false" /> </CheckoutOptions> <CheckinOptions> <option name="COMMENT" value="" /> <option name="KEEP_CHECKED_OUT" value="false" /> <option name="RECURSIVE" value="false" /> </CheckinOptions> <AddOptions> <option name="STORE_ONLY_LATEST_VERSION" value="false" /> <option name="CHECK_OUT_IMMEDIATELY" value="false" /> </AddOptions> <UndocheckoutOptions> <option name="MAKE_WRITABLE" value="false" /> <option name="REPLACE_LOCAL_COPY" value="2" /> <option name="RECURSIVE" value="false" /> </UndocheckoutOptions> <GetOptions> <option name="REPLACE_WRITABLE" value="0" /> <option name="MAKE_WRITABLE" value="false" /> <option name="ANSWER_NEGATIVELY" value="false" /> <option name="ANSWER_POSITIVELY" value="false" /> <option name="RECURSIVE" value="false" /> <option name="VERSION" /> </GetOptions> </component> <component name="XDebuggerManager"> <breakpoint-manager /> </component> <component name="XPathView.XPathProjectComponent"> <history /> <find-history /> </component> <component name="antWorkspaceConfiguration"> <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> <option name="FILTER_TARGETS" value="false" /> </component> <component name="atlassian-ide-plugin-workspace"> <option name="bambooConfiguration"> <BambooWorkspaceConfiguration> <option name="view"> <BambooViewConfigurationBean /> </option> </BambooWorkspaceConfiguration> </option> <option name="crucibleConfiguration"> <CrucibleWorkspaceConfiguration> <option name="crucibleFilters"> <CrucibleFiltersBean> <option name="manualFilter"> <CustomFilterBean> <option name="serverUid" value="bc006778-5a48-43b5-94b8-8a55cbed9b35" /> </CustomFilterBean> </option> <option name="recenltyOpenFilter"> <RecentlyOpenReviewsFilter /> </option> </CrucibleFiltersBean> </option> <option name="view"> <CrucibleViewConfigurationBean /> </option> </CrucibleWorkspaceConfiguration> </option> <option name="defaultCredentials"> <UserCfgBean /> </option> </component> <component name="atlassian-ide-plugin-workspace-issues"> <option name="view"> <JiraViewConfigurationBean> <option name="viewFilterId" value="" /> <option name="viewServerId" value="" /> </JiraViewConfigurationBean> </option> </component> <component name="editorHistoryManager"> + <entry file="jar:///System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/../Classes/classes.jar!/java/lang/System.class"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="85" column="117" selection-start="4306" selection-end="4306" vertical-scroll-proportion="0.2516704"> + <state line="91" column="10" selection-start="4436" selection-end="4436" vertical-scroll-proportion="0.5201794"> <folding /> </state> </provider> </entry> </component> <component name="masterDetails"> <option name="states"> <map> <entry key="Copyright.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="Errors.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="ProjectJDKs.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </SplitterProportionsDataImpl> </option> </UIState> </value> </entry> <entry key="ScopeChooserConfigurable.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> </map> </option> <option name="myStates"> <map> <entry key="Copyright.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="Errors.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="ProjectJDKs.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </SplitterProportionsDataImpl> </option> </UIState> </value> </entry> <entry key="ScopeChooserConfigurable.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> </map> </option> </component> </project> diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 2c133de..33ea359 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,222 +1,239 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 1)) (def y-cells ( * 48 1)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window - (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [fps (atom 0)]] - [(proxy [JPanel] [] (paint [graphics] - (paint-cells graphics cell-state) - (doto graphics (.setColor Color/WHITE) (.drawString (format "frames: %d" (swap! fps inc)) 0 10)))) - threadNumber - cell-state - ; since each window has a different set of threads, we calculate a "batch set" sized right for this window - ; so for the 1 thread window there will be one big batch with all cells listed - ; for a 2 thread window we will have 2 sets of cells listed - (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) - ]))) - - ; now we loop through the panels-and-state and materialize each one as a Swing JFrame + (def panels-and-state + (for [[threadNumber cell-state] initial-states-and-numprocs :let [frames (atom 0) lastts (atom 0) lastframes (atom 0) lastfps (atom 0)]] + [(proxy [JPanel] [] (paint [graphics] + ; paint the grid of cells + (paint-cells graphics cell-state) + ; increment our total frames painted + + ; now overlay a little info about frames per second and total frames drawn + ; figure out if we passed over 1 second since last mark + (let [totalframes (swap! frames inc) + ts (System/currentTimeMillis)] + ; fps (if secondpassed (reset! fps (- @frames @lastmark))) + (doto graphics + (.setColor Color/WHITE) + (.drawString (format "frames: %d, fps: %d" totalframes @lastfps) 0 10)) + ; reset lastts, lastfps, and lastframes if we just rolled over + (if (> ts (+ @lastts 1000)) + (do + (reset! lastts ts) + (reset! lastfps (- @frames @lastframes)) + (reset! lastframes @frames)))))) + threadNumber + cell-state + ; since each window has a different set of threads, we calculate a "batch set" sized right for this window + ; so for the 1 thread window there will be one big batch with all cells listed + ; for a 2 thread window we will have 2 sets of cells listed + (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) + ]))) + + ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread (when (and (not (= procs 3)) (not (= procs 5)) ) (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread (when (and (not (= procs 3)) (not (= procs 5))) (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] ( let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells)))) ; This is the all important function where parallelization kicks in (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "2")
sfraser/MultithreadedGameOfLife
c5d56a6a479d4d0e28c61af62f74978d3701a2b7
sources for clojure jar I just added
diff --git a/lib/clojure-sources-1.1.0-alpha-SNAPSHOT.jar b/lib/clojure-sources-1.1.0-alpha-SNAPSHOT.jar new file mode 100644 index 0000000..9d9cc97 Binary files /dev/null and b/lib/clojure-sources-1.1.0-alpha-SNAPSHOT.jar differ
sfraser/MultithreadedGameOfLife
d140e05ecf6b1621251097b5bfde360b861948cb
starting to add a "frames per second" display, and now using the latest clojure snapshot to see if transients speed things up
diff --git a/MultithreadedGameOfLife.iml b/MultithreadedGameOfLife.iml index a57f76f..e4928dc 100644 --- a/MultithreadedGameOfLife.iml +++ b/MultithreadedGameOfLife.iml @@ -1,18 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <module relativePaths="true" type="JAVA_MODULE" version="4"> <component name="FacetManager"> <facet type="Clojure" name="Clojure"> <configuration /> </facet> </component> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> - <orderEntry type="library" name="clojure-1.0" level="project" /> + <orderEntry type="module-library"> + <library> + <CLASSES> + <root url="jar://$MODULE_DIR$/lib/clojure-1.1.0-alpha-SNAPSHOT.jar!/" /> + </CLASSES> + <JAVADOC /> + <SOURCES /> + </library> + </orderEntry> </component> </module> diff --git a/MultithreadedGameOfLife.iws b/MultithreadedGameOfLife.iws index 1cf1b26..f0ae884 100644 --- a/MultithreadedGameOfLife.iws +++ b/MultithreadedGameOfLife.iws @@ -1,585 +1,593 @@ <?xml version="1.0" encoding="UTF-8"?> <project relativePaths="false" version="4"> + <component name="BookmarkManager"> + <editor_bookmark url="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" line="85" number="1" description="(doto graphics (.setColor Color/WHITE) (.drawStrin..." /> + </component> <component name="CCaseConfig"> <option name="checkoutReserved" value="false" /> <option name="markExternalChangeAsUpToDate" value="true" /> <option name="checkInUseHijack" value="true" /> <option name="useUcmModel" value="true" /> <option name="isOffline" value="false" /> <option name="synchOutside" value="false" /> <option name="isHistoryResticted" value="true" /> <option name="useIdenticalSwitch" value="true" /> <option name="synchActivitiesOnRefresh" value="true" /> <option name="lastScr" value="" /> <option name="scrTextFileName" value="" /> <option name="historyRevisionsNumber" value="4" /> </component> <component name="ChangeListManager"> <list default="true" name="Default" comment=""> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" afterPath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> + <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/lib/clojure-1.1.0-alpha-SNAPSHOT.jar" /> </list> <ignored path="MultithreadedGameOfLife.iws" /> <ignored path=".idea/workspace.xml" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="Commander"> <leftPanel /> <rightPanel /> <splitter proportion="0.5" /> </component> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> <option name="REVERSE_PATCH" value="false" /> </component> <component name="DaemonCodeAnalyzer"> <disable_hints /> </component> <component name="DebuggerManager"> <breakpoint_any> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> </breakpoint_any> <breakpoint_rules /> <ui_properties /> </component> <component name="FavoritesManager"> <favorites_list name="MultithreadedGameOfLife" /> </component> <component name="FileEditorManager"> <leaf> <file leaf-file-name="MultiThreadedLife.clj" pinned="false" current="true" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="153" column="21" selection-start="7980" selection-end="7980" vertical-scroll-proportion="0.54545456"> + <state line="85" column="117" selection-start="4306" selection-end="4306" vertical-scroll-proportion="0.2516704"> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="false" /> </FindUsagesManager> </component> <component name="Git.Settings"> <option name="GIT_EXECUTABLE" value="/usr/local/git/bin/git" /> </component> <component name="ModuleEditorState"> <option name="LAST_EDITED_MODULE_NAME" /> <option name="LAST_EDITED_TAB_NAME" /> </component> <component name="ProjectLevelVcsManager"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <OptionsSetting value="true" id="Undo Check Out" /> <OptionsSetting value="true" id="Get Latest Version" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> </PATH> </subPane> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <showStructure ProjectPane="false" /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> </component> <component name="PropertiesComponent"> - <property name="project.structure.proportion" value="0.0" /> + <property name="project.structure.proportion" value="0.15" /> <property name="MemberChooser.copyJavadoc" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder2" value="2" /> <property name="options.splitter.main.proportions" value="0.3" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder2" value="2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="893" /> <property name="GoToFile.includeJavaFiles" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="82" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="99" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="103" /> <property name="GoToClass.includeLibraries" value="false" /> <property name="options.splitter.details.proportions" value="0.2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder3" value="3" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder0" value="0" /> <property name="MemberChooser.showClasses" value="true" /> - <property name="project.structure.side.proportion" value="0.0" /> + <property name="project.structure.side.proportion" value="0.2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="94" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder3" value="3" /> - <property name="options.lastSelected" value="reference.settingsdialog.IDE.editor.colors.Font" /> + <property name="options.lastSelected" value="preferences.pluginManager" /> <property name="GoToClass.toSaveIncludeLibraries" value="false" /> <property name="RunManagerConfig.showSettingsBeforeRunnig" value="true" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder0" value="0" /> - <property name="project.structure.last.edited" value="Project" /> + <property name="project.structure.last.edited" value="Modules" /> <property name="options.searchVisible" value="true" /> <property name="MemberChooser.sorted" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder1" value="1" /> <property name="last_opened_file_path" value="/home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="115" /> <property name="dynamic.classpath" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="897" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="119" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder1" value="1" /> </component> + <component name="RegexUtilComponent" text="1900-01-01 2007/08/13 1900.01.01 1900 01 01 1900-01.01 1900 13 01 1900 02 31" mode="0" flags="0" regex="(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])" /> <component name="RunManager" selected="Clojure Script.MultiThreadedLife"> <configuration default="true" type="Remote" factoryName="Remote"> <option name="USE_SOCKET_TRANSPORT" value="true" /> <option name="SERVER_MODE" value="false" /> <option name="SHMEM_ADDRESS" value="javadebug" /> <option name="HOST" value="localhost" /> <option name="PORT" value="5005" /> </configuration> <configuration default="true" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="" /> <setting name="path" value="" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="" /> <setting name="repl" value="false" /> </configuration> <configuration default="true" type="Applet" factoryName="Applet"> <module name="" /> <option name="MAIN_CLASS_NAME" /> <option name="HTML_FILE_NAME" /> <option name="HTML_USED" value="false" /> <option name="WIDTH" value="400" /> <option name="HEIGHT" value="300" /> <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" /> <option name="VM_PARAMETERS" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> </configuration> <configuration default="true" type="JUnit" factoryName="JUnit" enabled="false" merge="false" runner="emma"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="TEST_OBJECT" value="class" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <envs /> </configuration> <configuration default="true" type="Application" factoryName="Application" enabled="false" merge="false" runner="emma"> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> </configuration> <configuration default="false" name="MultiThreadedLife" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="MultithreadedGameOfLife" /> <setting name="path" value="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="$PROJECT_DIR$/src/org/frasers/life" /> <setting name="repl" value="false" /> <RunnerSettings RunnerId="JProfiler"> <option name="WINDOW" value="false" /> <option name="JVMPI" value="false" /> <option name="INTERPRETED" value="false" /> </RunnerSettings> <RunnerSettings RunnerId="Run" /> <ConfigurationWrapper RunnerId="JProfiler" /> <ConfigurationWrapper RunnerId="Run" /> <method> <option name="Make" value="true" /> </method> </configuration> <list size="1"> <item index="0" class="java.lang.String" itemvalue="Clojure Script.MultiThreadedLife" /> </list> <configuration default="true" type="TestNG" factoryName="TestNG" enabled="false" merge="false" runner="emma"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="SUITE_NAME" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="GROUP_NAME" /> <option name="TEST_OBJECT" value="CLASS" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="OUTPUT_DIRECTORY" /> <option name="ANNOTATION_TYPE" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <option name="PROPERTIES_FILE" /> <envs /> <properties /> <listeners /> </configuration> <configuration name="&lt;template&gt;" type="WebApp" default="true" selected="false"> <Host>localhost</Host> <Port>5050</Port> </configuration> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="StarteamConfiguration"> <option name="SERVER" value="" /> <option name="PORT" value="49201" /> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="PROJECT" value="" /> <option name="VIEW" value="" /> <option name="ALTERNATIVE_WORKING_PATH" value="" /> <option name="LOCK_ON_CHECKOUT" value="false" /> <option name="UNLOCK_ON_CHECKIN" value="false" /> </component> <component name="StructureViewFactory"> <option name="AUTOSCROLL_MODE" value="true" /> <option name="AUTOSCROLL_FROM_SOURCE" value="false" /> <option name="ACTIVE_ACTIONS" value="" /> </component> <component name="SvnConfiguration"> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="LAST_MERGED_REVISION" /> <option name="UPDATE_RUN_STATUS" value="false" /> <option name="MERGE_DRY_RUN" value="false" /> <option name="MERGE_DIFF_USE_ANCESTRY" value="true" /> <option name="UPDATE_LOCK_ON_DEMAND" value="false" /> <option name="IGNORE_SPACES_IN_MERGE" value="false" /> <configuration useDefault="true">/home/sfraser/.subversion</configuration> <myIsUseDefaultProxy>false</myIsUseDefaultProxy> </component> <component name="TodoView" selected-index="0"> <todo-panel id="selected-file"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="all"> <are-packages-shown value="true" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="default-changelist"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="false" /> </todo-panel> </component> <component name="ToolWindowManager"> - <frame x="1" y="22" width="1280" height="774" extended-state="0" /> + <frame x="0" y="22" width="1280" height="774" extended-state="0" /> <editor active="false" /> <layout> <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Graphical Navigator" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Clojure REPL" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23235294" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" /> <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.24675325" sideWeight="0.64506173" order="0" side_tool="false" /> - <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.26461038" sideWeight="0.6455882" order="1" side_tool="false" /> + <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.26298702" sideWeight="0.7617647" order="1" side_tool="false" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" /> - <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" /> <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" /> <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="UML Diagrams" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="FindBugs-IDEA" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23734178" sideWeight="0.0" order="7" side_tool="false" /> - <window_info id="Run" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.34411764" sideWeight="0.5" order="2" side_tool="false" /> + <window_info id="Regex Tester" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.2367647" sideWeight="0.0" order="7" side_tool="false" /> + <window_info id="Run" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.22794117" sideWeight="0.5" order="2" side_tool="false" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="JProfiler" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32941177" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4117647" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> <window_info id="Atlassian " active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" /> <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> </layout> </component> <component name="VcsManagerConfiguration"> <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" /> <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" /> <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" /> <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" /> <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> - <option name="LAST_COMMIT_MESSAGE" /> + <option name="LAST_COMMIT_MESSAGE" value="update in IML appears to reference location of git binary" /> <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" /> <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" /> <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" /> <option name="ACTIVE_VCS_NAME" /> <option name="UPDATE_GROUP_BY_PACKAGES" value="false" /> <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" /> <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" /> + <MESSAGE value="update in IML appears to reference location of git binary" /> </component> <component name="VssConfiguration"> <option name="CLIENT_PATH" value="" /> <option name="SRCSAFEINI_PATH" value="" /> <option name="USER_NAME" value="" /> <option name="PWD" value="" /> <CheckoutOptions> <option name="COMMENT" value="" /> <option name="DO_NOT_GET_LATEST_VERSION" value="false" /> <option name="REPLACE_WRITABLE" value="false" /> <option name="RECURSIVE" value="false" /> </CheckoutOptions> <CheckinOptions> <option name="COMMENT" value="" /> <option name="KEEP_CHECKED_OUT" value="false" /> <option name="RECURSIVE" value="false" /> </CheckinOptions> <AddOptions> <option name="STORE_ONLY_LATEST_VERSION" value="false" /> <option name="CHECK_OUT_IMMEDIATELY" value="false" /> </AddOptions> <UndocheckoutOptions> <option name="MAKE_WRITABLE" value="false" /> <option name="REPLACE_LOCAL_COPY" value="2" /> <option name="RECURSIVE" value="false" /> </UndocheckoutOptions> <GetOptions> <option name="REPLACE_WRITABLE" value="0" /> <option name="MAKE_WRITABLE" value="false" /> <option name="ANSWER_NEGATIVELY" value="false" /> <option name="ANSWER_POSITIVELY" value="false" /> <option name="RECURSIVE" value="false" /> <option name="VERSION" /> </GetOptions> </component> <component name="XDebuggerManager"> <breakpoint-manager /> </component> <component name="XPathView.XPathProjectComponent"> <history /> <find-history /> </component> <component name="antWorkspaceConfiguration"> <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> <option name="FILTER_TARGETS" value="false" /> </component> <component name="atlassian-ide-plugin-workspace"> <option name="bambooConfiguration"> <BambooWorkspaceConfiguration> <option name="view"> <BambooViewConfigurationBean /> </option> </BambooWorkspaceConfiguration> </option> <option name="crucibleConfiguration"> <CrucibleWorkspaceConfiguration> <option name="crucibleFilters"> <CrucibleFiltersBean> <option name="manualFilter"> <CustomFilterBean> <option name="serverUid" value="bc006778-5a48-43b5-94b8-8a55cbed9b35" /> </CustomFilterBean> </option> <option name="recenltyOpenFilter"> <RecentlyOpenReviewsFilter /> </option> </CrucibleFiltersBean> </option> <option name="view"> <CrucibleViewConfigurationBean /> </option> </CrucibleWorkspaceConfiguration> </option> <option name="defaultCredentials"> <UserCfgBean /> </option> </component> <component name="atlassian-ide-plugin-workspace-issues"> <option name="view"> <JiraViewConfigurationBean> <option name="viewFilterId" value="" /> <option name="viewServerId" value="" /> </JiraViewConfigurationBean> </option> </component> <component name="editorHistoryManager"> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="153" column="21" selection-start="7980" selection-end="7980" vertical-scroll-proportion="0.54545456"> + <state line="85" column="117" selection-start="4306" selection-end="4306" vertical-scroll-proportion="0.2516704"> <folding /> </state> </provider> </entry> </component> <component name="masterDetails"> <option name="states"> <map> <entry key="Copyright.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="Errors.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="ProjectJDKs.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </SplitterProportionsDataImpl> </option> </UIState> </value> </entry> <entry key="ScopeChooserConfigurable.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> </map> </option> <option name="myStates"> <map> <entry key="Copyright.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="Errors.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="ProjectJDKs.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </SplitterProportionsDataImpl> </option> </UIState> </value> </entry> <entry key="ScopeChooserConfigurable.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> </map> </option> </component> </project> diff --git a/lib/clojure-1.1.0-alpha-SNAPSHOT.jar b/lib/clojure-1.1.0-alpha-SNAPSHOT.jar new file mode 100644 index 0000000..9b6768a Binary files /dev/null and b/lib/clojure-1.1.0-alpha-SNAPSHOT.jar differ diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 0972cf1..2c133de 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,220 +1,222 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! -(def x-cells ( * 32 2)) -(def y-cells ( * 48 2)) +(def x-cells ( * 32 1)) +(def y-cells ( * 48 1)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs - (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) - ] + (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) + ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window - (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] - [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) + (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs :let [fps (atom 0)]] + [(proxy [JPanel] [] (paint [graphics] + (paint-cells graphics cell-state) + (doto graphics (.setColor Color/WHITE) (.drawString (format "frames: %d" (swap! fps inc)) 0 10)))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread - (when (and (not (= procs 2)) (not (= procs 3)) ) + (when (and (not (= procs 3)) (not (= procs 5)) ) (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] ; todo - this is a horrible kludge to just show 4 versus 1 thread - (when (and (not (= procs 2)) (not (= procs 3))) + (when (and (not (= procs 3)) (not (= procs 5))) (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] ( let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells)))) ; This is the all important function where parallelization kicks in (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) -(-main "4") +(-main "2")
sfraser/MultithreadedGameOfLife
f190216d99407e6cc7e393d8450aac769a7cc46c
checking in IntelliJ project files before pull from linford
diff --git a/MultithreadedGameOfLife.ipr b/MultithreadedGameOfLife.ipr index 3f3d31c..af63655 100644 --- a/MultithreadedGameOfLife.ipr +++ b/MultithreadedGameOfLife.ipr @@ -1,260 +1,260 @@ <?xml version="1.0" encoding="UTF-8"?> <project relativePaths="false" version="4"> <component name="AntConfiguration"> <defaultAnt bundledAnt="true" /> </component> <component name="BuildJarProjectSettings"> <option name="BUILD_JARS_ON_MAKE" value="false" /> </component> <component name="CodeStyleSettingsManager"> <option name="PER_PROJECT_SETTINGS" /> <option name="USE_PER_PROJECT_SETTINGS" value="false" /> </component> <component name="CompilerConfiguration"> <option name="DEFAULT_COMPILER" value="Javac" /> <option name="DEPLOY_AFTER_MAKE" value="0" /> <resourceExtensions> <entry name=".+\.(properties|xml|html|dtd|tld)" /> <entry name=".+\.(gif|png|jpeg|jpg)" /> </resourceExtensions> <wildcardResourcePatterns> <entry name="?*.properties" /> <entry name="?*.xml" /> <entry name="?*.gif" /> <entry name="?*.png" /> <entry name="?*.jpeg" /> <entry name="?*.jpg" /> <entry name="?*.html" /> <entry name="?*.dtd" /> <entry name="?*.tld" /> <entry name="?*.ftl" /> </wildcardResourcePatterns> </component> <component name="CopyrightManager" default=""> <module2copyright /> </component> <component name="DependencyValidationManager"> <option name="SKIP_IMPORT_STATEMENTS" value="false" /> </component> <component name="EclipseCompilerSettings"> <option name="DEBUGGING_INFO" value="true" /> <option name="GENERATE_NO_WARNINGS" value="true" /> <option name="DEPRECATION" value="false" /> <option name="ADDITIONAL_OPTIONS_STRING" value="" /> <option name="MAXIMUM_HEAP_SIZE" value="128" /> </component> <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" /> <component name="IdProvider" IDEtalkID="B68953F18167018093CC8C1CA8D72796" /> <component name="InspectionProjectProfileManager"> <option name="PROJECT_PROFILE" value="Project Default" /> <option name="USE_PROJECT_LEVEL_SETTINGS" value="false" /> <scopes /> <profiles> <profile version="1.0" is_locked="false"> <option name="myName" value="Project Default" /> <option name="myLocal" value="false" /> </profile> </profiles> <list size="0" /> </component> <component name="JavacSettings"> <option name="DEBUGGING_INFO" value="true" /> <option name="GENERATE_NO_WARNINGS" value="false" /> <option name="DEPRECATION" value="true" /> <option name="ADDITIONAL_OPTIONS_STRING" value="" /> <option name="MAXIMUM_HEAP_SIZE" value="128" /> </component> <component name="JavadocGenerationManager"> <option name="OUTPUT_DIRECTORY" /> <option name="OPTION_SCOPE" value="protected" /> <option name="OPTION_HIERARCHY" value="true" /> <option name="OPTION_NAVIGATOR" value="true" /> <option name="OPTION_INDEX" value="true" /> <option name="OPTION_SEPARATE_INDEX" value="true" /> <option name="OPTION_DOCUMENT_TAG_USE" value="false" /> <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" /> <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" /> <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" /> <option name="OPTION_DEPRECATED_LIST" value="true" /> <option name="OTHER_OPTIONS" value="" /> <option name="HEAP_SIZE" /> <option name="LOCALE" /> <option name="OPEN_IN_BROWSER" value="true" /> </component> <component name="JikesSettings"> <option name="JIKES_PATH" value="" /> <option name="DEBUGGING_INFO" value="true" /> <option name="DEPRECATION" value="true" /> <option name="GENERATE_NO_WARNINGS" value="false" /> <option name="IS_EMACS_ERRORS_MODE" value="true" /> <option name="ADDITIONAL_OPTIONS_STRING" value="" /> </component> <component name="Palette2"> <group name="Swing"> <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" /> </item> <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" /> </item> <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" /> </item> <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true"> <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" /> </item> <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" /> <initial-values> <property name="text" value="Button" /> </initial-values> </item> <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> <initial-values> <property name="text" value="RadioButton" /> </initial-values> </item> <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> <initial-values> <property name="text" value="CheckBox" /> </initial-values> </item> <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" /> <initial-values> <property name="text" value="Label" /> </initial-values> </item> <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" /> </item> <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> <preferred-size width="200" height="200" /> </default-constraints> </item> <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> <preferred-size width="200" height="200" /> </default-constraints> </item> <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> </item> <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> </item> <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" /> </item> <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" /> </item> <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1"> <preferred-size width="-1" height="20" /> </default-constraints> </item> <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" /> </item> <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" /> </item> </group> </component> <component name="ProjectDetails"> <option name="projectName" value="MultithreadedGameOfLife" /> </component> <component name="ProjectFileVersion" converted="true" /> <component name="ProjectKey"> <option name="state" value="project:///home/sfraser/IdeaProjects/MultithreadedGameOfLife/MultithreadedGameOfLife.ipr" /> </component> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/MultithreadedGameOfLife.iml" filepath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" /> </modules> </component> - <component name="ProjectRootManager" version="2" languageLevel="JDK_1_5" assert-keyword="true" jdk-15="true" project-jdk-name="1.6" project-jdk-type="JavaSDK"> + <component name="ProjectRootManager" version="2" languageLevel="JDK_1_5" assert-keyword="true" jdk-15="true" project-jdk-name="1.6 (1)" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/out" /> </component> <component name="ResourceManagerContainer"> <option name="myResourceBundles"> <value> <list size="0" /> </value> </option> </component> <component name="RmicSettings"> <option name="IS_EANABLED" value="false" /> <option name="DEBUGGING_INFO" value="true" /> <option name="GENERATE_NO_WARNINGS" value="false" /> <option name="GENERATE_IIOP_STUBS" value="false" /> <option name="ADDITIONAL_OPTIONS_STRING" value="" /> </component> <component name="SvnBranchConfigurationManager"> <option name="myVersion" value="124" /> <option name="mySupportsUserInfoFilter" value="true" /> </component> <component name="VcsDirectoryMappings"> <mapping directory="" vcs="Git" /> </component> <component name="WebServicesPlugin" addRequiredLibraries="true" /> <component name="libraryTable"> <library name="clojure-1.0"> <CLASSES> <root url="jar://$PROJECT_DIR$/lib/clojure.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component> </project> diff --git a/MultithreadedGameOfLife.iws b/MultithreadedGameOfLife.iws index 0e08022..825caad 100644 --- a/MultithreadedGameOfLife.iws +++ b/MultithreadedGameOfLife.iws @@ -1,585 +1,671 @@ <?xml version="1.0" encoding="UTF-8"?> <project relativePaths="false" version="4"> <component name="CCaseConfig"> <option name="checkoutReserved" value="false" /> <option name="markExternalChangeAsUpToDate" value="true" /> <option name="checkInUseHijack" value="true" /> <option name="useUcmModel" value="true" /> <option name="isOffline" value="false" /> <option name="synchOutside" value="false" /> <option name="isHistoryResticted" value="true" /> <option name="useIdenticalSwitch" value="true" /> <option name="synchActivitiesOnRefresh" value="true" /> <option name="lastScr" value="" /> <option name="scrTextFileName" value="" /> <option name="historyRevisionsNumber" value="4" /> </component> <component name="ChangeListManager"> - <list default="true" name="Default" comment="" /> - <ignored path=".idea/workspace.xml" /> + <list default="true" name="Default" comment=""> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.ipr" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.ipr" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" afterPath="$PROJECT_DIR$/MultithreadedGameOfLife.iws" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" afterPath="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> + </list> <ignored path="MultithreadedGameOfLife.iws" /> + <ignored path=".idea/workspace.xml" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="Commander"> <leftPanel /> <rightPanel /> <splitter proportion="0.5" /> </component> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> <option name="REVERSE_PATCH" value="false" /> </component> <component name="DaemonCodeAnalyzer"> <disable_hints /> </component> <component name="DebuggerManager"> <breakpoint_any> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> <breakpoint> <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> <option name="CLASS_FILTERS_ENABLED" value="false" /> <option name="INSTANCE_FILTERS_ENABLED" value="false" /> <option name="CONDITION" value="" /> <option name="LOG_MESSAGE" value="" /> </breakpoint> </breakpoint_any> <breakpoint_rules /> <ui_properties /> </component> <component name="FavoritesManager"> <favorites_list name="MultithreadedGameOfLife" /> </component> <component name="FileEditorManager"> <leaf> <file leaf-file-name="MultiThreadedLife.clj" pinned="false" current="true" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="101" column="61" selection-start="4680" selection-end="4680" vertical-scroll-proportion="0.025423728"> + <state line="184" column="83" selection-start="9870" selection-end="9870" vertical-scroll-proportion="0.20173268"> + <folding /> + </state> + </provider> + </entry> + </file> + <file leaf-file-name="core.clj" pinned="false" current="false" current-in-tab="false"> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/clojure/core.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="1250" column="59" selection-start="40202" selection-end="40202" vertical-scroll-proportion="0.0"> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="false" /> </FindUsagesManager> </component> <component name="ModuleEditorState"> <option name="LAST_EDITED_MODULE_NAME" /> <option name="LAST_EDITED_TAB_NAME" /> </component> <component name="ProjectLevelVcsManager"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <OptionsSetting value="true" id="Undo Check Out" /> <OptionsSetting value="true" id="Get Latest Version" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="Libraries" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.LibraryGroupNode" /> + </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="src" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="life" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="MultithreadedGameOfLife" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="lib" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> </subPane> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <showStructure ProjectPane="false" /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> </component> <component name="PropertiesComponent"> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="82" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="119" /> + <property name="project.structure.last.edited" value="Facets" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="195" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="212" /> + <property name="project.structure.proportion" value="0.15" /> <property name="options.splitter.main.proportions" value="0.3" /> + <property name="RunManagerConfig.showSettingsBeforeRunnig" value="true" /> <property name="MemberChooser.sorted" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder1" value="1" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="94" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="201" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder0" value="0" /> <property name="last_opened_file_path" value="/home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="103" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="893" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="897" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="99" /> - <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="115" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="253" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="574" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="527" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="202" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="210" /> <property name="GoToClass.toSaveIncludeLibraries" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder2" value="2" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder3" value="3" /> <property name="MemberChooser.showClasses" value="true" /> <property name="GoToClass.includeLibraries" value="false" /> <property name="options.splitter.details.proportions" value="0.2" /> <property name="GoToFile.includeJavaFiles" value="false" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder0" value="0" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder3" value="3" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder1" value="1" /> <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder2" value="2" /> - <property name="options.lastSelected" value="com.intellij.openapi.vcs.configurable.VcsManagerConfigurable$4" /> + <property name="options.lastSelected" value="org.jetbrains.plugins.clojure.compiler.ClojureCompilerConfigurable" /> + <property name="project.structure.side.proportion" value="0.2" /> <property name="MemberChooser.copyJavadoc" value="false" /> <property name="options.searchVisible" value="true" /> <property name="dynamic.classpath" value="false" /> </component> <component name="RunManager" selected="Clojure Script.MultiThreadedLife"> - <tempConfiguration default="false" name="MultiThreadedLife" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> - <module name="MultithreadedGameOfLife" /> - <setting name="path" value="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> - <setting name="vmparams" value="" /> - <setting name="params" value="" /> - <setting name="workDir" value="$PROJECT_DIR$/src/org/frasers/life" /> - <setting name="repl" value="false" /> - <RunnerSettings RunnerId="Run" /> - <ConfigurationWrapper RunnerId="Run" /> - <method> - <option name="Make" value="true" /> - </method> - </tempConfiguration> <configuration default="true" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> <module name="" /> <setting name="path" value="" /> <setting name="vmparams" value="" /> <setting name="params" value="" /> <setting name="workDir" value="" /> <setting name="repl" value="false" /> </configuration> <configuration default="true" type="Remote" factoryName="Remote"> <option name="USE_SOCKET_TRANSPORT" value="true" /> <option name="SERVER_MODE" value="false" /> <option name="SHMEM_ADDRESS" value="javadebug" /> <option name="HOST" value="localhost" /> <option name="PORT" value="5005" /> </configuration> <configuration default="true" type="TestNG" factoryName="TestNG" enabled="false" merge="false" runner="emma"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="SUITE_NAME" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="GROUP_NAME" /> <option name="TEST_OBJECT" value="CLASS" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="OUTPUT_DIRECTORY" /> <option name="ANNOTATION_TYPE" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <option name="PROPERTIES_FILE" /> <envs /> <properties /> <listeners /> </configuration> <configuration default="true" type="Applet" factoryName="Applet"> <module name="" /> <option name="MAIN_CLASS_NAME" /> <option name="HTML_FILE_NAME" /> <option name="HTML_USED" value="false" /> <option name="WIDTH" value="400" /> <option name="HEIGHT" value="300" /> <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" /> <option name="VM_PARAMETERS" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> </configuration> <configuration default="true" type="Application" factoryName="Application" enabled="false" merge="false" runner="emma"> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> </configuration> <configuration default="true" type="JUnit" factoryName="JUnit" enabled="false" merge="false" runner="emma"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="TEST_OBJECT" value="class" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="moduleWithDependencies" /> </option> <envs /> </configuration> + <configuration default="false" name="MultiThreadedLife" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> + <module name="MultithreadedGameOfLife" /> + <setting name="path" value="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> + <setting name="vmparams" value="" /> + <setting name="params" value="" /> + <setting name="workDir" value="$PROJECT_DIR$/src/org/frasers/life" /> + <setting name="repl" value="false" /> + <RunnerSettings RunnerId="Debug"> + <option name="DEBUG_PORT" value="36064" /> + <option name="TRANSPORT" value="0" /> + <option name="LOCAL" value="true" /> + </RunnerSettings> + <RunnerSettings RunnerId="Run" /> + <ConfigurationWrapper RunnerId="Debug" /> + <ConfigurationWrapper RunnerId="Run" /> + <method> + <option name="Make" value="true" /> + </method> + </configuration> <list size="1"> <item index="0" class="java.lang.String" itemvalue="Clojure Script.MultiThreadedLife" /> </list> <configuration name="&lt;template&gt;" type="WebApp" default="true" selected="false"> <Host>localhost</Host> <Port>5050</Port> </configuration> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="StarteamConfiguration"> <option name="SERVER" value="" /> <option name="PORT" value="49201" /> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="PROJECT" value="" /> <option name="VIEW" value="" /> <option name="ALTERNATIVE_WORKING_PATH" value="" /> <option name="LOCK_ON_CHECKOUT" value="false" /> <option name="UNLOCK_ON_CHECKIN" value="false" /> </component> <component name="StructureViewFactory"> <option name="AUTOSCROLL_MODE" value="true" /> <option name="AUTOSCROLL_FROM_SOURCE" value="false" /> <option name="ACTIVE_ACTIONS" value="" /> </component> <component name="SvnConfiguration"> <option name="USER" value="" /> <option name="PASSWORD" value="" /> <option name="LAST_MERGED_REVISION" /> <option name="UPDATE_RUN_STATUS" value="false" /> <option name="MERGE_DRY_RUN" value="false" /> <option name="MERGE_DIFF_USE_ANCESTRY" value="true" /> <option name="UPDATE_LOCK_ON_DEMAND" value="false" /> <option name="IGNORE_SPACES_IN_MERGE" value="false" /> <configuration useDefault="true">/home/sfraser/.subversion</configuration> <myIsUseDefaultProxy>false</myIsUseDefaultProxy> </component> <component name="TodoView" selected-index="0"> <todo-panel id="selected-file"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="all"> <are-packages-shown value="true" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="default-changelist"> <are-packages-shown value="false" /> <are-modules-shown value="false" /> <flatten-packages value="false" /> <is-autoscroll-to-source value="false" /> </todo-panel> </component> <component name="ToolWindowManager"> - <frame x="15" y="22" width="1280" height="774" extended-state="0" /> + <frame x="424" y="-81" width="1276" height="1000" extended-state="0" /> <editor active="true" /> <layout> <window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23734178" sideWeight="0.0" order="7" side_tool="false" /> + <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23612139" sideWeight="0.0" order="7" side_tool="false" /> <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" /> - <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.39970392" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="8" side_tool="false" /> + <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="9" side_tool="false" /> <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4129747" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.30235294" sideWeight="0.5" order="10" side_tool="false" /> + <window_info id="Clojure REPL" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32938564" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="11" side_tool="false" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" /> <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" /> <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> - <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24675325" sideWeight="0.75158226" order="0" side_tool="false" /> - <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> - <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.32922825" sideWeight="0.0" order="0" side_tool="false" /> + <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="12" side_tool="false" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" /> - <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32911393" sideWeight="0.5" order="2" side_tool="false" /> + <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.31754255" sideWeight="0.9918831" order="2" side_tool="false" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" /> + <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32941177" sideWeight="0.5" order="13" side_tool="false" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" /> </layout> </component> <component name="VcsManagerConfiguration"> <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" /> <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" /> <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" /> <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" /> <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" /> <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> - <option name="LAST_COMMIT_MESSAGE" /> + <option name="LAST_COMMIT_MESSAGE" value="&#10;# Brief commit desciption here&#10;finally got the agents showing perf difference between threads!&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;the key was that in determine-new-state-in-agent I did not have parens &#10;around the &quot;doall&quot; call, which must have turned the whole thing into a form that&#10;got evaluated LATER on&#10;" /> <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" /> <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" /> <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" /> <option name="ACTIVE_VCS_NAME" /> <option name="UPDATE_GROUP_BY_PACKAGES" value="false" /> <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" /> <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;fixed static ref&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;Call to Math/ceil was incorrect&#10;&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;formatting&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;auto formatted code&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;fixed defct in code from groups&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;need to pass a [vector] to doseq&#10;&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;rolling back to when multithreaded worked&#10;&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;commented out the experimental calc-state, put the old calc-state and &#10;update-batch -of-new-cell-states back in. Now the windows with more threads&#10;are running faster again.&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;got old and new code in here (working and not working)&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;I took out some of the doall calls in calc-state to try and isolate why it is not&#10;faster than the old nested pmaps. I am still not sure, but it might be more &#10;a function of how the &quot;update-batch-of-new-cells&quot; would write the changes&#10;to new-cells. Maybe that was why the old code was actually faster. I am going to&#10;move on to trying to use straight vectors and the agent pattern to carve up&#10;the work and totally avoid refs as much as possible.&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;minor cleanup&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;about ready to add agents - going to give each window its own vector&#10;of agents and have it pass those into a function that will call and them and then&#10;wait till they are all done&#10;&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;removing unneeded procs param to toggle-thread&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;I didn't really need to pass in &quot;procs&quot; as it was equal to the count of batch-set&#10;&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;finally got agents working BUT... still not faster&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;agents were tricky but I got them in there. I think Lazy stuff is holding me back&#10;&#10;" /> + <MESSAGE value="&#10;# Brief commit desciption here&#10;finally got the agents showing perf difference between threads!&#10;# Full commit description here (comment lines starting with '#' will not be included)&#10;the key was that in determine-new-state-in-agent I did not have parens &#10;around the &quot;doall&quot; call, which must have turned the whole thing into a form that&#10;got evaluated LATER on&#10;" /> </component> <component name="VssConfiguration"> <option name="CLIENT_PATH" value="" /> <option name="SRCSAFEINI_PATH" value="" /> <option name="USER_NAME" value="" /> <option name="PWD" value="" /> <CheckoutOptions> <option name="COMMENT" value="" /> <option name="DO_NOT_GET_LATEST_VERSION" value="false" /> <option name="REPLACE_WRITABLE" value="false" /> <option name="RECURSIVE" value="false" /> </CheckoutOptions> <CheckinOptions> <option name="COMMENT" value="" /> <option name="KEEP_CHECKED_OUT" value="false" /> <option name="RECURSIVE" value="false" /> </CheckinOptions> <AddOptions> <option name="STORE_ONLY_LATEST_VERSION" value="false" /> <option name="CHECK_OUT_IMMEDIATELY" value="false" /> </AddOptions> <UndocheckoutOptions> <option name="MAKE_WRITABLE" value="false" /> <option name="REPLACE_LOCAL_COPY" value="2" /> <option name="RECURSIVE" value="false" /> </UndocheckoutOptions> <GetOptions> <option name="REPLACE_WRITABLE" value="0" /> <option name="MAKE_WRITABLE" value="false" /> <option name="ANSWER_NEGATIVELY" value="false" /> <option name="ANSWER_POSITIVELY" value="false" /> <option name="RECURSIVE" value="false" /> <option name="VERSION" /> </GetOptions> </component> <component name="XDebuggerManager"> <breakpoint-manager /> </component> <component name="XPathView.XPathProjectComponent"> <history /> <find-history /> </component> <component name="antWorkspaceConfiguration"> <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> <option name="FILTER_TARGETS" value="false" /> </component> <component name="editorHistoryManager"> <entry file="file:///home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> <state line="5" column="12" selection-start="0" selection-end="8693" vertical-scroll-proportion="0.0"> <folding /> </state> </provider> </entry> + <entry file="file://$PROJECT_DIR$/MultithreadedGameOfLife.ipr"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="file://$PROJECT_DIR$/MultithreadedGameOfLife.iws"> + <provider selected="true" editor-type-id="text-editor"> + <state line="568" column="42" selection-start="28941" selection-end="28941" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/META-INF/MANIFEST.MF"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/clojure/lang/RT.class"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/clojure/lang/AFn.class"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/clojure/lang/Var.class"> + <provider selected="true" editor-type-id="text-editor"> + <state line="96" column="28" selection-start="4358" selection-end="4358" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="jar://$PROJECT_DIR$/lib/clojure.jar!/clojure/core.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="1250" column="59" selection-start="40202" selection-end="40202" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> <provider selected="true" editor-type-id="text-editor"> - <state line="101" column="61" selection-start="4680" selection-end="4680" vertical-scroll-proportion="0.025423728"> + <state line="184" column="83" selection-start="9870" selection-end="9870" vertical-scroll-proportion="0.20173268"> <folding /> </state> </provider> </entry> </component> <component name="masterDetails"> <option name="states"> <map> <entry key="Copyright.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="Errors.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="ProjectJDKs.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </SplitterProportionsDataImpl> </option> </UIState> </value> </entry> <entry key="ScopeChooserConfigurable.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> </map> </option> <option name="myStates"> <map> <entry key="Copyright.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="Errors.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> <entry key="ProjectJDKs.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </SplitterProportionsDataImpl> </option> </UIState> </value> </entry> <entry key="ScopeChooserConfigurable.UI"> <value> <UIState> <option name="proportions"> <SplitterProportionsDataImpl /> </option> </UIState> </value> </entry> </map> </option> </component> </project>
sfraser/MultithreadedGameOfLife
be9c8a58d5ba63c7b89b08a94938aa72b2b01ab0
formatting - should be no material changes, though maybe I made the grid smaller as I was running on my laptop
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index c7de410..0972cf1 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,223 +1,220 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) - '(java.awt BorderLayout Dimension Color) - '(java.awt.event ActionListener)) + '(java.awt BorderLayout Dimension Color) + '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! -(def x-cells ( * 32 3)) -(def y-cells ( * 48 3)) +(def x-cells ( * 32 2)) +(def y-cells ( * 48 2)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] - ; Example of setting number of threads based on the number of processors the JVM can see - ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) + ; Example of setting number of threads based on the number of processors the JVM can see + ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) - ; First we need to calculate the initial state that all the windows will start with - ; easiest way is to have one map of cell states that all windows initially point to - ; so we create an initial-state ref - ; and then set up a list of vectors: [threadNumber initialState] + ; First we need to calculate the initial state that all the windows will start with + ; easiest way is to have one map of cell states that all windows initially point to + ; so we create an initial-state ref + ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs - (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) - ] - - ; this is where we calculate the initial state of the first window - ; since all windows are initially pointing at the same map, everyone will - ; start up with the same state - ; Would be nice to clean this up so at starup each window actually had the same number of colors it - ; will have after the user hits "start" + (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) + ] + + ; this is where we calculate the initial state of the first window + ; since all windows are initially pointing at the same map, everyone will + ; start up with the same state + ; Would be nice to clean this up so at starup each window actually had the same number of colors it + ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) - ; make a list of vectors of [panel procs cell-state precalced-batch-sets] - ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different - ; sized for each window + ; make a list of vectors of [panel procs cell-state precalced-batch-sets] + ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different + ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] - [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) - threadNumber - cell-state - ; since each window has a different set of threads, we calculate a "batch set" sized right for this window - ; so for the 1 thread window there will be one big batch with all cells listed - ; for a 2 thread window we will have 2 sets of cells listed - (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) - ]))) - - ; now we loop through the panels-and-state and materialize each one as a Swing JFrame - ; @param panel JPanel with a threadNumber and current set of cell-state - ; @param procs number of processes to use for this panel - ; @param cell-state current cell-state for this panel - ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel + [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) + threadNumber + cell-state + ; since each window has a different set of threads, we calculate a "batch set" sized right for this window + ; so for the 1 thread window there will be one big batch with all cells listed + ; for a 2 thread window we will have 2 sets of cells listed + (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) + ]))) + + ; now we loop through the panels-and-state and materialize each one as a Swing JFrame + ; @param panel JPanel with a threadNumber and current set of cell-state + ; @param procs number of processes to use for this panel + ; @param cell-state current cell-state for this panel + ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] - ; todo - this is a horrible kludge to just show 4 versus 1 thread + ; todo - this is a horrible kludge to just show 4 versus 1 thread (when (and (not (= procs 2)) (not (= procs 3)) ) - (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) - b (JButton. "Start")] - - (doto f - (.setLayout (BorderLayout.)) - (.setLocation 100 100) - (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) - (.add b BorderLayout/SOUTH) - (.add panel BorderLayout/CENTER) - (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) - (.pack) - (.setVisible true)) - - (. b addActionListener - (proxy [ActionListener] [] - (actionPerformed [evt] - (reset! running (false? @running)) - (. b (setText (if @running "Start" "Stop"))) - (doseq [[panel procs cell-state batch-set] panels-and-state] - ; todo - this is a horrible kludge to just show 4 versus 1 thread - (when (and (not (= procs 2)) (not (= procs 3))) - (toggle-thread panel cell-state batch-set))))))))) + (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) + b (JButton. "Start")] + + (doto f + (.setLayout (BorderLayout.)) + (.setLocation 100 100) + (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) + (.add b BorderLayout/SOUTH) + (.add panel BorderLayout/CENTER) + (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) + (.pack) + (.setVisible true)) + + (. b addActionListener + (proxy [ActionListener] [] + (actionPerformed [evt] + (reset! running (false? @running)) + (. b (setText (if @running "Start" "Stop"))) + (doseq [[panel procs cell-state batch-set] panels-and-state] + ; todo - this is a horrible kludge to just show 4 versus 1 thread + (when (and (not (= procs 2)) (not (= procs 3))) + (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] - (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) - (ref-set counter 0) - (alter counter inc)))) + (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) + (ref-set counter 0) + (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) -; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) - (not (= empty-color - (mycells - [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] - :alive))] + (not (= empty-color + (mycells + [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] + :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) -; replaced this with a single threaded reduce in calc-state -; DEPRECATED - need to eliminate this, it is only used in startup now + ; replaced this with a single threaded reduce in calc-state + ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync - ; first here is the vector of [x y], and second is the state - (dorun (map #(commute new-cells assoc (first %) (second %)) - list-of-batches)))) + ; first here is the vector of [x y], and second is the state + (dorun (map #(commute new-cells assoc (first %) (second %)) + list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] ( let [thread-color (nth color-list (next-color-fn))] doall (map - #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] - ;first here is the vector of [x y], and second is the state (color) - [[(first %) (second %)] new-cell-state]) - batch-cells))) + #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells))) -; This is the all important function where parallelization kicks in -; DEPRECATED - need to eliminate this, it is only used in startup now + ; This is the all important function where parallelization kicks in + ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) - (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) - batch-set))) + (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) + batch-set))) (dosync (ref-set mycells @new-cells)))) -; this function is passed into an agent -; the agent will map it onto its batch-set, updating the batch-set as it goes + ; this function is passed into an agent + ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] - ; it is AMAZING how this one change - putting the doall into a form - made all the differnce on perf due to no more lazy - (doall (map #( - let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] - ;first here is the vector of [x y], and second is the state (color) - [[(first %) (second %)] new-cell-state]) - batch-cells)))) - -; This is the all important function where parallelization kicks in + (doall (map #(let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells)))) + + ; This is the all important function where parallelization kicks in (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] - (doseq [a agents] - (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) - (apply await agents) - (dosync (ref-set mycells - (reduce into {} - (map deref agents)))))) - -; Type Hint here makes a huge performance difference for the better + (doseq [a agents] + (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) + (apply await agents) + (dosync (ref-set mycells + (reduce into {} + (map deref agents)))))) + + ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) -; This is what gets called when you hit the State/Stop button + ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) - (ref-set mycounter 0) - (alter mycounter inc))) - ; set of agents for this windows exclusive use for painting - there will be one agent per batch set - ; assert (count (batch-set) == procs) - ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) - ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] - ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) + (ref-set mycounter 0) + (alter mycounter inc))) + ; set of agents for this windows exclusive use for painting - there will be one agent per batch set + ; assert (count (batch-set) == procs) + ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) + ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] + ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. - #(loop [] - ;(calc-state determine-new-state mycells batch-set next-color) - (calc-state-with-agents batch-set mycells next-color-fn) - (.repaint panel) - ;(if life-delay (Thread/sleep life-delay)) - (if @running (recur)))) - start))))) + #(loop [] + ;(calc-state determine-new-state mycells batch-set next-color) + (calc-state-with-agents batch-set mycells next-color-fn) + (.repaint panel) + ;(if life-delay (Thread/sleep life-delay)) + (if @running (recur)))) + start))))) (-main "4")
sfraser/MultithreadedGameOfLife
50dd1a689aaf55731c063b4b6e3f84cded5454ed
finally got the agents showing perf difference between threads! the key was that in determine-new-state-in-agent I did not have parens around the "doall" call, which must have turned the whole thing into a form that got evaluated LATER on
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 295fa2f..c7de410 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,218 +1,223 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] - + ; todo - this is a horrible kludge to just show 4 versus 1 thread + (when (and (not (= procs 2)) (not (= procs 3)) ) (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) - (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set))))))) + (doseq [[panel procs cell-state batch-set] panels-and-state] + ; todo - this is a horrible kludge to just show 4 versus 1 thread + (when (and (not (= procs 2)) (not (= procs 3))) + (toggle-thread panel cell-state batch-set))))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] ( let [thread-color (nth color-list (next-color-fn))] doall (map #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; This is the all important function where parallelization kicks in ; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; this function is passed into an agent ; the agent will map it onto its batch-set, updating the batch-set as it goes (defn determine-new-state-in-agent [batch-cells mycells next-color-fn] (let [thread-color (nth color-list (next-color-fn))] - doall (map #( + ; it is AMAZING how this one change - putting the doall into a form - made all the differnce on perf due to no more lazy + (doall (map #( let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) - batch-cells))) + batch-cells)))) ; This is the all important function where parallelization kicks in (defn calc-state-with-agents [batch-set mycells next-color-fn] (let [agents (map #(agent %) batch-set)] (doseq [a agents] (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) (apply await agents) (dosync (ref-set mycells (reduce into {} (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] ;(calc-state determine-new-state mycells batch-set next-color) (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "4")
sfraser/MultithreadedGameOfLife
1491b0337133521d7ba97d91a4a11cdf308e8b92
finally got agents working BUT... still not faster agents were tricky but I got them in there. I think Lazy stuff is holding me back
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 595cfcd..295fa2f 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,214 +1,218 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) - (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] + (not (= empty-color + (mycells + [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state +; DEPRECATED - need to eliminate this, it is only used in startup now (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) -(defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] - ( let [thread-color (nth color-list (next-color))] +(defn calc-batch-of-new-cell-states [cell-state-fn batch-cells mycells next-color-fn] + ( let [thread-color (nth color-list (next-color-fn))] doall (map - #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] + #(let [new-cell-state (if (cell-state-fn (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) -; I am here - incorporate this in as a way of distributing the work -;(defn vector-pmap [f v] -; (let [n (.. Runtime getRuntime availableProcessors) -; sectn (int (Math/ceil (/ (count v) n))) -; agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) -; (range n)) -; ] -; (doseq [a agents] -; (send a #(doall (map f %)))) -; (apply await agents) -; (into [] (apply concat (map deref agents))))) - - ; This is the all important function where parallelization kicks in +; DEPRECATED - need to eliminate this, it is only used in startup now (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) -; Gonna try and reduce shared state - instead we'll put the states into the -; batches and be done with it -(defn calc-state-new [cell-state-fn mycells batch-set next-color] - (let [new-cells (reduce into {} - ; This no longer seems to run faster with more threads? Why? Tried doall, no difference - ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? - (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) - batch-set))] - (dosync (ref-set mycells new-cells)))) +; this function is passed into an agent +; the agent will map it onto its batch-set, updating the batch-set as it goes +(defn determine-new-state-in-agent [batch-cells mycells next-color-fn] + (let [thread-color (nth color-list (next-color-fn))] + doall (map #( + let [new-cell-state (if (determine-new-state (first %) (second %) mycells) thread-color empty-color)] + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells))) + +; This is the all important function where parallelization kicks in +(defn calc-state-with-agents [batch-set mycells next-color-fn] + (let [agents (map #(agent %) batch-set)] + (doseq [a agents] + (send a (fn [batch] (determine-new-state-in-agent batch mycells next-color-fn)))) + (apply await agents) + (dosync (ref-set mycells + (reduce into {} + (map deref agents)))))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) num-batches (count batch-set) - next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) + next-color-fn #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) (alter mycounter inc))) ; set of agents for this windows exclusive use for painting - there will be one agent per batch set ; assert (count (batch-set) == procs) - ; agents (map #(agent %) batch-set) + ; sectn (int (Math.ceil (/ (count mycells) num-batches ))) + ; this should give each agent its own subset of this windows cells, each vec element is: [[x y] color] + ; agents (map #(agent (subvec mycells (* sectn %) (min (count mycells) (+ (* sectn %))))) (range num-batches)) ] (do (. (Thread. #(loop [] - (calc-state determine-new-state mycells batch-set next-color) + ;(calc-state determine-new-state mycells batch-set next-color) + (calc-state-with-agents batch-set mycells next-color-fn) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) -(-main "3") +(-main "4")
sfraser/MultithreadedGameOfLife
fbad5a7665d5c327536a73624f3e8d3f2bb331ce
removing unneeded procs param to toggle-thread I didn't really need to pass in "procs" as it was equal to the count of batch-set
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index c1bfe9b..595cfcd 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,209 +1,214 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state ; Would be nice to clean this up so at starup each window actually had the same number of colors it ; will have after the user hits "start" (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) - (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) + (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; I am here - incorporate this in as a way of distributing the work ;(defn vector-pmap [f v] ; (let [n (.. Runtime getRuntime availableProcessors) ; sectn (int (Math/ceil (/ (count v) n))) ; agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) ; (range n)) ; ] ; (doseq [a agents] ; (send a #(doall (map f %)))) ; (apply await agents) ; (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in (defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it (defn calc-state-new [cell-state-fn mycells batch-set next-color] (let [new-cells (reduce into {} ; This no longer seems to run faster with more threads? Why? Tried doall, no difference ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))] (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button -(defn toggle-thread [panel mycells batch-set procs] +(defn toggle-thread [panel mycells batch-set] (if @running (let [mycounter (ref 0) - next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) + num-batches (count batch-set) + next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec num-batches))) (ref-set mycounter 0) - (alter mycounter inc)))] + (alter mycounter inc))) + ; set of agents for this windows exclusive use for painting - there will be one agent per batch set + ; assert (count (batch-set) == procs) + ; agents (map #(agent %) batch-set) + ] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
2c56e1c532b8706c07f19098129fd0b2894a498e
minor cleanup about ready to add agents - going to give each window its own vector of agents and have it pass those into a function that will call and them and then wait till they are all done
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index cfab4ff..c1bfe9b 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,209 +1,209 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) - ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique - ; set of cells to work on - (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) - ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs - (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] + (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))]) + ] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state - (calc-state determine-initial-state initial-state initial-batch-sets next-color) + ; Would be nice to clean this up so at starup each window actually had the same number of colors it + ; will have after the user hits "start" + (let [initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))] + (calc-state determine-initial-state initial-state initial-batch-sets next-color)) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; I am here - incorporate this in as a way of distributing the work ;(defn vector-pmap [f v] ; (let [n (.. Runtime getRuntime availableProcessors) ; sectn (int (Math/ceil (/ (count v) n))) ; agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) ; (range n)) ; ] ; (doseq [a agents] ; (send a #(doall (map f %)))) ; (apply await agents) ; (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in -(defn calc-state-old [cell-state mycells batch-set next-color] +(defn calc-state [cell-state-fn mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) - (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) + (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it -(defn calc-state [cell-state mycells batch-set next-color] +(defn calc-state-new [cell-state-fn mycells batch-set next-color] (let [new-cells (reduce into {} ; This no longer seems to run faster with more threads? Why? Tried doall, no difference ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? - (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) + (pmap #(calc-batch-of-new-cell-states cell-state-fn % mycells next-color) batch-set))] (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) - (ref-set mycounter 0) - (alter mycounter inc)))] + (ref-set mycounter 0) + (alter mycounter inc)))] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
d3862b18597a4e213adee1a27bf18805af00d29b
got old and new code in here (working and not working) I took out some of the doall calls in calc-state to try and isolate why it is not faster than the old nested pmaps. I am still not sure, but it might be more a function of how the "update-batch-of-new-cells" would write the changes to new-cells. Maybe that was why the old code was actually faster. I am going to move on to trying to use straight vectors and the agent pattern to carve up the work and totally avoid refs as much as possible.
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index a111708..cfab4ff 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,209 +1,209 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique ; set of cells to work on (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state (calc-state determine-initial-state initial-state initial-batch-sets next-color) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state (defn update-batch-of-new-cells [new-cells list-of-batches] (dosync ; first here is the vector of [x y], and second is the state (dorun (map #(commute new-cells assoc (first %) (second %)) list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; I am here - incorporate this in as a way of distributing the work -(defn vector-pmap [f v] - (let [n (.. Runtime getRuntime availableProcessors) - sectn (int (Math/ceil (/ (count v) n))) - agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) - (range n)) - ] - (doseq [a agents] - (send a #(doall (map f %)))) - (apply await agents) - (into [] (apply concat (map deref agents))))) +;(defn vector-pmap [f v] +; (let [n (.. Runtime getRuntime availableProcessors) +; sectn (int (Math/ceil (/ (count v) n))) +; agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) +; (range n)) +; ] +; (doseq [a agents] +; (send a #(doall (map f %)))) +; (apply await agents) +; (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in -(defn calc-state [cell-state mycells batch-set next-color] +(defn calc-state-old [cell-state mycells batch-set next-color] (let [new-cells (ref {})] (dorun (pmap #(update-batch-of-new-cells new-cells %) (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) batch-set))) (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it -;(defn calc-state [cell-state mycells batch-set next-color] -; (let [new-cells (doall (reduce into {} -; ; This no longer seems to run faster with more threads? Why? Tried doall, no difference -; ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? -; (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) -; batch-set))))] -; (dosync (ref-set mycells new-cells)))) +(defn calc-state [cell-state mycells batch-set next-color] + (let [new-cells (reduce into {} + ; This no longer seems to run faster with more threads? Why? Tried doall, no difference + ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? + (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) + batch-set))] + (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) (ref-set mycounter 0) (alter mycounter inc)))] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
d3142e3718d58f14344b1791d10743cd3793ec09
rolling back to when multithreaded worked commented out the experimental calc-state, put the old calc-state and update-batch -of-new-cell-states back in. Now the windows with more threads are running faster again.
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index e65e909..a111708 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,209 +1,209 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique ; set of cells to work on (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state (calc-state determine-initial-state initial-state initial-batch-sets next-color) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state -;(defn update-batch-of-new-cells [new-cells list-of-batches] -; (dosync -; ; first here is the vector of [x y], and second is the state -; (dorun (map #(commute new-cells assoc (first %) (second %)) -; list-of-batches)))) +(defn update-batch-of-new-cells [new-cells list-of-batches] + (dosync + ; first here is the vector of [x y], and second is the state + (dorun (map #(commute new-cells assoc (first %) (second %)) + list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; I am here - incorporate this in as a way of distributing the work (defn vector-pmap [f v] (let [n (.. Runtime getRuntime availableProcessors) sectn (int (Math/ceil (/ (count v) n))) agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) (range n)) ] (doseq [a agents] (send a #(doall (map f %)))) (apply await agents) (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in -;(defn calc-state-old [cell-state mycells batch-set next-color] -; (let [new-cells (ref {})] -; (dorun (pmap #(update-batch-of-new-cells new-cells %) -; (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) -; batch-set))) -; (dosync (ref-set mycells @new-cells)))) +(defn calc-state [cell-state mycells batch-set next-color] + (let [new-cells (ref {})] + (dorun (pmap #(update-batch-of-new-cells new-cells %) + (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) + batch-set))) + (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it -(defn calc-state [cell-state mycells batch-set next-color] - (let [new-cells (doall (reduce into {} - ; This no longer seems to run faster with more threads? Why? Tried doall, no difference - ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? - (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) - batch-set))))] - (dosync (ref-set mycells new-cells)))) +;(defn calc-state [cell-state mycells batch-set next-color] +; (let [new-cells (doall (reduce into {} +; ; This no longer seems to run faster with more threads? Why? Tried doall, no difference +; ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? +; (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) +; batch-set))))] +; (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) (ref-set mycounter 0) (alter mycounter inc)))] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
9fd7466a4411032325bc9cc01a217cf3bad15da7
fixed defct in code from groups need to pass a [vector] to doseq
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index cec40de..e65e909 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,211 +1,209 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique ; set of cells to work on (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state (calc-state determine-initial-state initial-state initial-batch-sets next-color) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ;(defn update-batch-of-new-cells [new-cells list-of-batches] ; (dosync ; ; first here is the vector of [x y], and second is the state ; (dorun (map #(commute new-cells assoc (first %) (second %)) ; list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; I am here - incorporate this in as a way of distributing the work (defn vector-pmap [f v] (let [n (.. Runtime getRuntime availableProcessors) sectn (int (Math/ceil (/ (count v) n))) - agents (map #(agent (subvec v - (* sectn %) - (min (count v) (+ (* sectn %) - sectn)))) - (range n))] - (doseq a agents + agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) + (range n)) + ] + (doseq [a agents] (send a #(doall (map f %)))) (apply await agents) (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in ;(defn calc-state-old [cell-state mycells batch-set next-color] ; (let [new-cells (ref {})] ; (dorun (pmap #(update-batch-of-new-cells new-cells %) ; (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) ; batch-set))) ; (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it (defn calc-state [cell-state mycells batch-set next-color] (let [new-cells (doall (reduce into {} ; This no longer seems to run faster with more threads? Why? Tried doall, no difference ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) batch-set))))] (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) (ref-set mycounter 0) (alter mycounter inc)))] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
da5ebb5cede9930bffe104094440553c690430c2
formatting auto formatted code
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index ab82e85..cec40de 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,211 +1,211 @@ (comment - ; Parallelized Conway's Game of Life - ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. - ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. - ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run - ) + ; Parallelized Conway's Game of Life + ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. + ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. + ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run + ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique ; set of cells to work on (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs - (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] + (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state (calc-state determine-initial-state initial-state initial-batch-sets next-color) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] - [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) - threadNumber - cell-state - ; since each window has a different set of threads, we calculate a "batch set" sized right for this window - ; so for the 1 thread window there will be one big batch with all cells listed - ; for a 2 thread window we will have 2 sets of cells listed - (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) - ]))) + [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) + threadNumber + cell-state + ; since each window has a different set of threads, we calculate a "batch set" sized right for this window + ; so for the 1 thread window there will be one big batch with all cells listed + ; for a 2 thread window we will have 2 sets of cells listed + (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) + ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) - (ref-set counter 0) - (alter counter inc)))) + (ref-set counter 0) + (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) - (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] - :alive))] + (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] + :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ;(defn update-batch-of-new-cells [new-cells list-of-batches] ; (dosync ; ; first here is the vector of [x y], and second is the state ; (dorun (map #(commute new-cells assoc (first %) (second %)) ; list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map - #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] - ;first here is the vector of [x y], and second is the state (color) - [[(first %) (second %)] new-cell-state]) - batch-cells))) + #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells))) ; I am here - incorporate this in as a way of distributing the work (defn vector-pmap [f v] (let [n (.. Runtime getRuntime availableProcessors) sectn (int (Math/ceil (/ (count v) n))) agents (map #(agent (subvec v - (* sectn %) - (min (count v) (+ (* sectn %) -sectn)))) - (range n))] + (* sectn %) + (min (count v) (+ (* sectn %) + sectn)))) + (range n))] (doseq a agents (send a #(doall (map f %)))) (apply await agents) (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in ;(defn calc-state-old [cell-state mycells batch-set next-color] ; (let [new-cells (ref {})] ; (dorun (pmap #(update-batch-of-new-cells new-cells %) ; (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) ; batch-set))) ; (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it (defn calc-state [cell-state mycells batch-set next-color] (let [new-cells (doall (reduce into {} - ; This no longer seems to run faster with more threads? Why? Tried doall, no difference - ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? - (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) - batch-set))))] + ; This no longer seems to run faster with more threads? Why? Tried doall, no difference + ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? + (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) + batch-set))))] (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) - (ref-set mycounter 0) - (alter mycounter inc)))] + (ref-set mycounter 0) + (alter mycounter inc)))] (do (. (Thread. - #(loop [] - (calc-state determine-new-state mycells batch-set next-color) - (.repaint panel) - ;(if life-delay (Thread/sleep life-delay)) - (if @running (recur)))) + #(loop [] + (calc-state determine-new-state mycells batch-set next-color) + (.repaint panel) + ;(if life-delay (Thread/sleep life-delay)) + (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
fa54963efc1289830f75544c4fe918dda5126647
fixed static ref Call to Math/ceil was incorrect
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 2036383..ab82e85 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,211 +1,211 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique ; set of cells to work on (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state (calc-state determine-initial-state initial-state initial-batch-sets next-color) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ;(defn update-batch-of-new-cells [new-cells list-of-batches] ; (dosync ; ; first here is the vector of [x y], and second is the state ; (dorun (map #(commute new-cells assoc (first %) (second %)) ; list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) ; I am here - incorporate this in as a way of distributing the work (defn vector-pmap [f v] (let [n (.. Runtime getRuntime availableProcessors) - sectn (int (Math.ceil (/ (count v) n))) + sectn (int (Math/ceil (/ (count v) n))) agents (map #(agent (subvec v (* sectn %) (min (count v) (+ (* sectn %) sectn)))) (range n))] (doseq a agents (send a #(doall (map f %)))) (apply await agents) (into [] (apply concat (map deref agents))))) ; This is the all important function where parallelization kicks in ;(defn calc-state-old [cell-state mycells batch-set next-color] ; (let [new-cells (ref {})] ; (dorun (pmap #(update-batch-of-new-cells new-cells %) ; (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) ; batch-set))) ; (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it (defn calc-state [cell-state mycells batch-set next-color] (let [new-cells (doall (reduce into {} ; This no longer seems to run faster with more threads? Why? Tried doall, no difference ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) batch-set))))] (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) (ref-set mycounter 0) (alter mycounter inc)))] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
146503ec887a6f774ad7c06e03a500c900648b70
adding new function This is some code from the thread here: http://groups.google.com/group/clojure/msg/dd68dc457572f096? I want to adapt the program to use this pattern
diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj index 52b6035..2036383 100644 --- a/src/org/frasers/life/MultiThreadedLife.clj +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -1,196 +1,211 @@ (comment ; Parallelized Conway's Game of Life ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run ) (ns org.frasers.life.MultiThreadedLife (:gen-class)) (import '(javax.swing JFrame JPanel JButton) '(java.awt BorderLayout Dimension Color) '(java.awt.event ActionListener)) ; Used across all threads to signal if we are running or not ; Toggled by the Start/Stop buttons (def running (atom false)) ; Dimensions of the grid - make this bigger if you have more horsepower! (def x-cells ( * 32 3)) (def y-cells ( * 48 3)) ;(def x-cells 32) ;(def y-cells 32) ; sequence of all the valid coordinates (def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) ; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids (def cell-size 5) ; Optional Thread sleep factor to slow simulation down - I usually don't use it (def life-delay 0) ; Used when we randomly populate the grid at startup (def life-initial-prob 3) ; example of how to set available-procs based on numner of processors JVM has access to. ; Not using this root level binding right now because we are passing in the number ; ;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) ;(def available-procs 8) ;(def available-procs) ;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) ;(def batch-sets) (defn calc-state) (defn determine-initial-state) (defn paint-cells) (defn toggle-thread) ; some things we will use to give each thread a different color (def counter (ref 0)) (def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) (def num-colors (count color-list)) (def empty-color Color/BLACK) (defn next-color) (defn -main[arg-num-threads] ; Example of setting number of threads based on the number of processors the JVM can see ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) (def num-threads (Integer/parseInt arg-num-threads)) ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique ; set of cells to work on (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) ; First we need to calculate the initial state that all the windows will start with ; easiest way is to have one map of cell states that all windows initially point to ; so we create an initial-state ref ; and then set up a list of vectors: [threadNumber initialState] (let [initial-state (ref {}) initial-states-and-numprocs (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] ; this is where we calculate the initial state of the first window ; since all windows are initially pointing at the same map, everyone will ; start up with the same state (calc-state determine-initial-state initial-state initial-batch-sets next-color) ; make a list of vectors of [panel procs cell-state precalced-batch-sets] ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different ; sized for each window (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) threadNumber cell-state ; since each window has a different set of threads, we calculate a "batch set" sized right for this window ; so for the 1 thread window there will be one big batch with all cells listed ; for a 2 thread window we will have 2 sets of cells listed (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) ]))) ; now we loop through the panels-and-state and materialize each one as a Swing JFrame ; @param panel JPanel with a threadNumber and current set of cell-state ; @param procs number of processes to use for this panel ; @param cell-state current cell-state for this panel ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel (doseq [[panel procs cell-state batch-set] panels-and-state] (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) b (JButton. "Start")] (doto f (.setLayout (BorderLayout.)) (.setLocation 100 100) (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) (.add b BorderLayout/SOUTH) (.add panel BorderLayout/CENTER) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.pack) (.setVisible true)) (. b addActionListener (proxy [ActionListener] [] (actionPerformed [evt] (reset! running (false? @running)) (. b (setText (if @running "Start" "Stop"))) (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) ) (defn next-color [] (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) (ref-set counter 0) (alter counter inc)))) (defn determine-initial-state [x y _] (= 0 (rand-int life-initial-prob))) ; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) (defn determine-new-state [x y mycells] (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] :when (and (not (= 0 dx dy)) (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] :alive))] (if (not (= (mycells [x y]) empty-color)) (< 1 alive 4) (= alive 3)))) ; replaced this with a single threaded reduce in calc-state ;(defn update-batch-of-new-cells [new-cells list-of-batches] ; (dosync ; ; first here is the vector of [x y], and second is the state ; (dorun (map #(commute new-cells assoc (first %) (second %)) ; list-of-batches)))) (defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] ( let [thread-color (nth color-list (next-color))] doall (map #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] ;first here is the vector of [x y], and second is the state (color) [[(first %) (second %)] new-cell-state]) batch-cells))) +; I am here - incorporate this in as a way of distributing the work +(defn vector-pmap [f v] + (let [n (.. Runtime getRuntime availableProcessors) + sectn (int (Math.ceil (/ (count v) n))) + agents (map #(agent (subvec v + (* sectn %) + (min (count v) (+ (* sectn %) +sectn)))) + (range n))] + (doseq a agents + (send a #(doall (map f %)))) + (apply await agents) + (into [] (apply concat (map deref agents))))) + + ; This is the all important function where parallelization kicks in ;(defn calc-state-old [cell-state mycells batch-set next-color] ; (let [new-cells (ref {})] ; (dorun (pmap #(update-batch-of-new-cells new-cells %) ; (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) ; batch-set))) ; (dosync (ref-set mycells @new-cells)))) ; Gonna try and reduce shared state - instead we'll put the states into the ; batches and be done with it (defn calc-state [cell-state mycells batch-set next-color] (let [new-cells (doall (reduce into {} ; This no longer seems to run faster with more threads? Why? Tried doall, no difference ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) batch-set))))] (dosync (ref-set mycells new-cells)))) ; Type Hint here makes a huge performance difference for the better (defn paint-cells [#^java.awt.Graphics graphics mycells] (doseq [[[x,y] state] @mycells] (doto graphics (.setColor state) (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) ; This is what gets called when you hit the State/Stop button (defn toggle-thread [panel mycells batch-set procs] (if @running (let [mycounter (ref 0) next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) (ref-set mycounter 0) (alter mycounter inc)))] (do (. (Thread. #(loop [] (calc-state determine-new-state mycells batch-set next-color) (.repaint panel) ;(if life-delay (Thread/sleep life-delay)) (if @running (recur)))) start))))) (-main "3")
sfraser/MultithreadedGameOfLife
bdb46b0024a6e776dcfde121903d2c24253bcf27
Initial import, though I think this was already in the Home repo
diff --git a/MultithreadedGameOfLife.iml b/MultithreadedGameOfLife.iml new file mode 100644 index 0000000..a57f76f --- /dev/null +++ b/MultithreadedGameOfLife.iml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module relativePaths="true" type="JAVA_MODULE" version="4"> + <component name="FacetManager"> + <facet type="Clojure" name="Clojure"> + <configuration /> + </facet> + </component> + <component name="NewModuleRootManager" inherit-compiler-output="true"> + <exclude-output /> + <content url="file://$MODULE_DIR$"> + <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> + </content> + <orderEntry type="inheritedJdk" /> + <orderEntry type="sourceFolder" forTests="false" /> + <orderEntry type="library" name="clojure-1.0" level="project" /> + </component> +</module> + diff --git a/MultithreadedGameOfLife.ipr b/MultithreadedGameOfLife.ipr new file mode 100644 index 0000000..3f3d31c --- /dev/null +++ b/MultithreadedGameOfLife.ipr @@ -0,0 +1,260 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project relativePaths="false" version="4"> + <component name="AntConfiguration"> + <defaultAnt bundledAnt="true" /> + </component> + <component name="BuildJarProjectSettings"> + <option name="BUILD_JARS_ON_MAKE" value="false" /> + </component> + <component name="CodeStyleSettingsManager"> + <option name="PER_PROJECT_SETTINGS" /> + <option name="USE_PER_PROJECT_SETTINGS" value="false" /> + </component> + <component name="CompilerConfiguration"> + <option name="DEFAULT_COMPILER" value="Javac" /> + <option name="DEPLOY_AFTER_MAKE" value="0" /> + <resourceExtensions> + <entry name=".+\.(properties|xml|html|dtd|tld)" /> + <entry name=".+\.(gif|png|jpeg|jpg)" /> + </resourceExtensions> + <wildcardResourcePatterns> + <entry name="?*.properties" /> + <entry name="?*.xml" /> + <entry name="?*.gif" /> + <entry name="?*.png" /> + <entry name="?*.jpeg" /> + <entry name="?*.jpg" /> + <entry name="?*.html" /> + <entry name="?*.dtd" /> + <entry name="?*.tld" /> + <entry name="?*.ftl" /> + </wildcardResourcePatterns> + </component> + <component name="CopyrightManager" default=""> + <module2copyright /> + </component> + <component name="DependencyValidationManager"> + <option name="SKIP_IMPORT_STATEMENTS" value="false" /> + </component> + <component name="EclipseCompilerSettings"> + <option name="DEBUGGING_INFO" value="true" /> + <option name="GENERATE_NO_WARNINGS" value="true" /> + <option name="DEPRECATION" value="false" /> + <option name="ADDITIONAL_OPTIONS_STRING" value="" /> + <option name="MAXIMUM_HEAP_SIZE" value="128" /> + </component> + <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" /> + <component name="IdProvider" IDEtalkID="B68953F18167018093CC8C1CA8D72796" /> + <component name="InspectionProjectProfileManager"> + <option name="PROJECT_PROFILE" value="Project Default" /> + <option name="USE_PROJECT_LEVEL_SETTINGS" value="false" /> + <scopes /> + <profiles> + <profile version="1.0" is_locked="false"> + <option name="myName" value="Project Default" /> + <option name="myLocal" value="false" /> + </profile> + </profiles> + <list size="0" /> + </component> + <component name="JavacSettings"> + <option name="DEBUGGING_INFO" value="true" /> + <option name="GENERATE_NO_WARNINGS" value="false" /> + <option name="DEPRECATION" value="true" /> + <option name="ADDITIONAL_OPTIONS_STRING" value="" /> + <option name="MAXIMUM_HEAP_SIZE" value="128" /> + </component> + <component name="JavadocGenerationManager"> + <option name="OUTPUT_DIRECTORY" /> + <option name="OPTION_SCOPE" value="protected" /> + <option name="OPTION_HIERARCHY" value="true" /> + <option name="OPTION_NAVIGATOR" value="true" /> + <option name="OPTION_INDEX" value="true" /> + <option name="OPTION_SEPARATE_INDEX" value="true" /> + <option name="OPTION_DOCUMENT_TAG_USE" value="false" /> + <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" /> + <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" /> + <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" /> + <option name="OPTION_DEPRECATED_LIST" value="true" /> + <option name="OTHER_OPTIONS" value="" /> + <option name="HEAP_SIZE" /> + <option name="LOCALE" /> + <option name="OPEN_IN_BROWSER" value="true" /> + </component> + <component name="JikesSettings"> + <option name="JIKES_PATH" value="" /> + <option name="DEBUGGING_INFO" value="true" /> + <option name="DEPRECATION" value="true" /> + <option name="GENERATE_NO_WARNINGS" value="false" /> + <option name="IS_EMACS_ERRORS_MODE" value="true" /> + <option name="ADDITIONAL_OPTIONS_STRING" value="" /> + </component> + <component name="Palette2"> + <group name="Swing"> + <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" /> + </item> + <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" /> + </item> + <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" /> + </item> + <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true"> + <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" /> + </item> + <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" /> + <initial-values> + <property name="text" value="Button" /> + </initial-values> + </item> + <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> + <initial-values> + <property name="text" value="RadioButton" /> + </initial-values> + </item> + <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> + <initial-values> + <property name="text" value="CheckBox" /> + </initial-values> + </item> + <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" /> + <initial-values> + <property name="text" value="Label" /> + </initial-values> + </item> + <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> + <preferred-size width="150" height="-1" /> + </default-constraints> + </item> + <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> + <preferred-size width="150" height="-1" /> + </default-constraints> + </item> + <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> + <preferred-size width="150" height="-1" /> + </default-constraints> + </item> + <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> + <preferred-size width="150" height="50" /> + </default-constraints> + </item> + <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> + <preferred-size width="150" height="50" /> + </default-constraints> + </item> + <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> + <preferred-size width="150" height="50" /> + </default-constraints> + </item> + <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" /> + </item> + <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> + <preferred-size width="150" height="50" /> + </default-constraints> + </item> + <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3"> + <preferred-size width="150" height="50" /> + </default-constraints> + </item> + <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> + <preferred-size width="150" height="50" /> + </default-constraints> + </item> + <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> + <preferred-size width="200" height="200" /> + </default-constraints> + </item> + <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> + <preferred-size width="200" height="200" /> + </default-constraints> + </item> + <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> + </item> + <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> + </item> + <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" /> + </item> + <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" /> + </item> + <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1"> + <preferred-size width="-1" height="20" /> + </default-constraints> + </item> + <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" /> + </item> + <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" /> + </item> + </group> + </component> + <component name="ProjectDetails"> + <option name="projectName" value="MultithreadedGameOfLife" /> + </component> + <component name="ProjectFileVersion" converted="true" /> + <component name="ProjectKey"> + <option name="state" value="project:///home/sfraser/IdeaProjects/MultithreadedGameOfLife/MultithreadedGameOfLife.ipr" /> + </component> + <component name="ProjectModuleManager"> + <modules> + <module fileurl="file://$PROJECT_DIR$/MultithreadedGameOfLife.iml" filepath="$PROJECT_DIR$/MultithreadedGameOfLife.iml" /> + </modules> + </component> + <component name="ProjectRootManager" version="2" languageLevel="JDK_1_5" assert-keyword="true" jdk-15="true" project-jdk-name="1.6" project-jdk-type="JavaSDK"> + <output url="file://$PROJECT_DIR$/out" /> + </component> + <component name="ResourceManagerContainer"> + <option name="myResourceBundles"> + <value> + <list size="0" /> + </value> + </option> + </component> + <component name="RmicSettings"> + <option name="IS_EANABLED" value="false" /> + <option name="DEBUGGING_INFO" value="true" /> + <option name="GENERATE_NO_WARNINGS" value="false" /> + <option name="GENERATE_IIOP_STUBS" value="false" /> + <option name="ADDITIONAL_OPTIONS_STRING" value="" /> + </component> + <component name="SvnBranchConfigurationManager"> + <option name="myVersion" value="124" /> + <option name="mySupportsUserInfoFilter" value="true" /> + </component> + <component name="VcsDirectoryMappings"> + <mapping directory="" vcs="Git" /> + </component> + <component name="WebServicesPlugin" addRequiredLibraries="true" /> + <component name="libraryTable"> + <library name="clojure-1.0"> + <CLASSES> + <root url="jar://$PROJECT_DIR$/lib/clojure.jar!/" /> + </CLASSES> + <JAVADOC /> + <SOURCES /> + </library> + </component> +</project> + diff --git a/MultithreadedGameOfLife.iws b/MultithreadedGameOfLife.iws new file mode 100644 index 0000000..0e08022 --- /dev/null +++ b/MultithreadedGameOfLife.iws @@ -0,0 +1,585 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project relativePaths="false" version="4"> + <component name="CCaseConfig"> + <option name="checkoutReserved" value="false" /> + <option name="markExternalChangeAsUpToDate" value="true" /> + <option name="checkInUseHijack" value="true" /> + <option name="useUcmModel" value="true" /> + <option name="isOffline" value="false" /> + <option name="synchOutside" value="false" /> + <option name="isHistoryResticted" value="true" /> + <option name="useIdenticalSwitch" value="true" /> + <option name="synchActivitiesOnRefresh" value="true" /> + <option name="lastScr" value="" /> + <option name="scrTextFileName" value="" /> + <option name="historyRevisionsNumber" value="4" /> + </component> + <component name="ChangeListManager"> + <list default="true" name="Default" comment="" /> + <ignored path=".idea/workspace.xml" /> + <ignored path="MultithreadedGameOfLife.iws" /> + </component> + <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> + <component name="Commander"> + <leftPanel /> + <rightPanel /> + <splitter proportion="0.5" /> + </component> + <component name="CreatePatchCommitExecutor"> + <option name="PATCH_PATH" value="" /> + <option name="REVERSE_PATCH" value="false" /> + </component> + <component name="DaemonCodeAnalyzer"> + <disable_hints /> + </component> + <component name="DebuggerManager"> + <breakpoint_any> + <breakpoint> + <option name="NOTIFY_CAUGHT" value="true" /> + <option name="NOTIFY_UNCAUGHT" value="true" /> + <option name="ENABLED" value="false" /> + <option name="LOG_ENABLED" value="false" /> + <option name="LOG_EXPRESSION_ENABLED" value="false" /> + <option name="SUSPEND_POLICY" value="SuspendAll" /> + <option name="COUNT_FILTER_ENABLED" value="false" /> + <option name="COUNT_FILTER" value="0" /> + <option name="CONDITION_ENABLED" value="false" /> + <option name="CLASS_FILTERS_ENABLED" value="false" /> + <option name="INSTANCE_FILTERS_ENABLED" value="false" /> + <option name="CONDITION" value="" /> + <option name="LOG_MESSAGE" value="" /> + </breakpoint> + <breakpoint> + <option name="NOTIFY_CAUGHT" value="true" /> + <option name="NOTIFY_UNCAUGHT" value="true" /> + <option name="ENABLED" value="false" /> + <option name="LOG_ENABLED" value="false" /> + <option name="LOG_EXPRESSION_ENABLED" value="false" /> + <option name="SUSPEND_POLICY" value="SuspendAll" /> + <option name="COUNT_FILTER_ENABLED" value="false" /> + <option name="COUNT_FILTER" value="0" /> + <option name="CONDITION_ENABLED" value="false" /> + <option name="CLASS_FILTERS_ENABLED" value="false" /> + <option name="INSTANCE_FILTERS_ENABLED" value="false" /> + <option name="CONDITION" value="" /> + <option name="LOG_MESSAGE" value="" /> + </breakpoint> + </breakpoint_any> + <breakpoint_rules /> + <ui_properties /> + </component> + <component name="FavoritesManager"> + <favorites_list name="MultithreadedGameOfLife" /> + </component> + <component name="FileEditorManager"> + <leaf> + <file leaf-file-name="MultiThreadedLife.clj" pinned="false" current="true" current-in-tab="true"> + <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="101" column="61" selection-start="4680" selection-end="4680" vertical-scroll-proportion="0.025423728"> + <folding /> + </state> + </provider> + </entry> + </file> + </leaf> + </component> + <component name="FindManager"> + <FindUsagesManager> + <setting name="OPEN_NEW_TAB" value="false" /> + </FindUsagesManager> + </component> + <component name="ModuleEditorState"> + <option name="LAST_EDITED_MODULE_NAME" /> + <option name="LAST_EDITED_TAB_NAME" /> + </component> + <component name="ProjectLevelVcsManager"> + <OptionsSetting value="true" id="Add" /> + <OptionsSetting value="true" id="Remove" /> + <OptionsSetting value="true" id="Checkout" /> + <OptionsSetting value="true" id="Update" /> + <OptionsSetting value="true" id="Status" /> + <OptionsSetting value="true" id="Edit" /> + <OptionsSetting value="true" id="Undo Check Out" /> + <OptionsSetting value="true" id="Get Latest Version" /> + <ConfirmationsSetting value="0" id="Add" /> + <ConfirmationsSetting value="0" id="Remove" /> + </component> + <component name="ProjectPane"> + <subPane> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="src" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="life" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="MultithreadedGameOfLife" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="lib" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> + </PATH_ELEMENT> + </PATH> + </subPane> + </component> + <component name="ProjectReloadState"> + <option name="STATE" value="0" /> + </component> + <component name="ProjectView"> + <navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5"> + <flattenPackages /> + <showMembers /> + <showModules /> + <showLibraryContents /> + <hideEmptyPackages /> + <abbreviatePackageNames /> + <showStructure ProjectPane="false" /> + <autoscrollToSource /> + <autoscrollFromSource /> + <sortByType /> + </navigator> + </component> + <component name="PropertiesComponent"> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth0" value="82" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth1" value="119" /> + <property name="options.splitter.main.proportions" value="0.3" /> + <property name="MemberChooser.sorted" value="false" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder1" value="1" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth0" value="94" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder0" value="0" /> + <property name="last_opened_file_path" value="/home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth2" value="103" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth3" value="893" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatWidth3" value="897" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth2" value="99" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeWidth1" value="115" /> + <property name="GoToClass.toSaveIncludeLibraries" value="false" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder2" value="2" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_flatOrder3" value="3" /> + <property name="MemberChooser.showClasses" value="true" /> + <property name="GoToClass.includeLibraries" value="false" /> + <property name="options.splitter.details.proportions" value="0.2" /> + <property name="GoToFile.includeJavaFiles" value="false" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder0" value="0" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder3" value="3" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder1" value="1" /> + <property name="FileHistory.git4idea.history.GitHistoryProvider_treeOrder2" value="2" /> + <property name="options.lastSelected" value="com.intellij.openapi.vcs.configurable.VcsManagerConfigurable$4" /> + <property name="MemberChooser.copyJavadoc" value="false" /> + <property name="options.searchVisible" value="true" /> + <property name="dynamic.classpath" value="false" /> + </component> + <component name="RunManager" selected="Clojure Script.MultiThreadedLife"> + <tempConfiguration default="false" name="MultiThreadedLife" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> + <module name="MultithreadedGameOfLife" /> + <setting name="path" value="$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj" /> + <setting name="vmparams" value="" /> + <setting name="params" value="" /> + <setting name="workDir" value="$PROJECT_DIR$/src/org/frasers/life" /> + <setting name="repl" value="false" /> + <RunnerSettings RunnerId="Run" /> + <ConfigurationWrapper RunnerId="Run" /> + <method> + <option name="Make" value="true" /> + </method> + </tempConfiguration> + <configuration default="true" type="ClojureScriptRunConfiguration" factoryName="Clojure Script"> + <module name="" /> + <setting name="path" value="" /> + <setting name="vmparams" value="" /> + <setting name="params" value="" /> + <setting name="workDir" value="" /> + <setting name="repl" value="false" /> + </configuration> + <configuration default="true" type="Remote" factoryName="Remote"> + <option name="USE_SOCKET_TRANSPORT" value="true" /> + <option name="SERVER_MODE" value="false" /> + <option name="SHMEM_ADDRESS" value="javadebug" /> + <option name="HOST" value="localhost" /> + <option name="PORT" value="5005" /> + </configuration> + <configuration default="true" type="TestNG" factoryName="TestNG" enabled="false" merge="false" runner="emma"> + <module name="" /> + <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> + <option name="ALTERNATIVE_JRE_PATH" /> + <option name="SUITE_NAME" /> + <option name="PACKAGE_NAME" /> + <option name="MAIN_CLASS_NAME" /> + <option name="METHOD_NAME" /> + <option name="GROUP_NAME" /> + <option name="TEST_OBJECT" value="CLASS" /> + <option name="VM_PARAMETERS" /> + <option name="PARAMETERS" /> + <option name="WORKING_DIRECTORY" /> + <option name="OUTPUT_DIRECTORY" /> + <option name="ANNOTATION_TYPE" /> + <option name="ENV_VARIABLES" /> + <option name="PASS_PARENT_ENVS" value="true" /> + <option name="ADDITIONAL_CLASS_PATH" /> + <option name="TEST_SEARCH_SCOPE"> + <value defaultName="moduleWithDependencies" /> + </option> + <option name="PROPERTIES_FILE" /> + <envs /> + <properties /> + <listeners /> + </configuration> + <configuration default="true" type="Applet" factoryName="Applet"> + <module name="" /> + <option name="MAIN_CLASS_NAME" /> + <option name="HTML_FILE_NAME" /> + <option name="HTML_USED" value="false" /> + <option name="WIDTH" value="400" /> + <option name="HEIGHT" value="300" /> + <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" /> + <option name="VM_PARAMETERS" /> + <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> + <option name="ALTERNATIVE_JRE_PATH" /> + </configuration> + <configuration default="true" type="Application" factoryName="Application" enabled="false" merge="false" runner="emma"> + <option name="MAIN_CLASS_NAME" /> + <option name="VM_PARAMETERS" /> + <option name="PROGRAM_PARAMETERS" /> + <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> + <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> + <option name="ALTERNATIVE_JRE_PATH" /> + <option name="ENABLE_SWING_INSPECTOR" value="false" /> + <option name="ENV_VARIABLES" /> + <option name="PASS_PARENT_ENVS" value="true" /> + <module name="" /> + <envs /> + </configuration> + <configuration default="true" type="JUnit" factoryName="JUnit" enabled="false" merge="false" runner="emma"> + <module name="" /> + <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> + <option name="ALTERNATIVE_JRE_PATH" /> + <option name="PACKAGE_NAME" /> + <option name="MAIN_CLASS_NAME" /> + <option name="METHOD_NAME" /> + <option name="TEST_OBJECT" value="class" /> + <option name="VM_PARAMETERS" /> + <option name="PARAMETERS" /> + <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> + <option name="ENV_VARIABLES" /> + <option name="PASS_PARENT_ENVS" value="true" /> + <option name="ADDITIONAL_CLASS_PATH" /> + <option name="TEST_SEARCH_SCOPE"> + <value defaultName="moduleWithDependencies" /> + </option> + <envs /> + </configuration> + <list size="1"> + <item index="0" class="java.lang.String" itemvalue="Clojure Script.MultiThreadedLife" /> + </list> + <configuration name="&lt;template&gt;" type="WebApp" default="true" selected="false"> + <Host>localhost</Host> + <Port>5050</Port> + </configuration> + </component> + <component name="ShelveChangesManager" show_recycled="false" /> + <component name="StarteamConfiguration"> + <option name="SERVER" value="" /> + <option name="PORT" value="49201" /> + <option name="USER" value="" /> + <option name="PASSWORD" value="" /> + <option name="PROJECT" value="" /> + <option name="VIEW" value="" /> + <option name="ALTERNATIVE_WORKING_PATH" value="" /> + <option name="LOCK_ON_CHECKOUT" value="false" /> + <option name="UNLOCK_ON_CHECKIN" value="false" /> + </component> + <component name="StructureViewFactory"> + <option name="AUTOSCROLL_MODE" value="true" /> + <option name="AUTOSCROLL_FROM_SOURCE" value="false" /> + <option name="ACTIVE_ACTIONS" value="" /> + </component> + <component name="SvnConfiguration"> + <option name="USER" value="" /> + <option name="PASSWORD" value="" /> + <option name="LAST_MERGED_REVISION" /> + <option name="UPDATE_RUN_STATUS" value="false" /> + <option name="MERGE_DRY_RUN" value="false" /> + <option name="MERGE_DIFF_USE_ANCESTRY" value="true" /> + <option name="UPDATE_LOCK_ON_DEMAND" value="false" /> + <option name="IGNORE_SPACES_IN_MERGE" value="false" /> + <configuration useDefault="true">/home/sfraser/.subversion</configuration> + <myIsUseDefaultProxy>false</myIsUseDefaultProxy> + </component> + <component name="TodoView" selected-index="0"> + <todo-panel id="selected-file"> + <are-packages-shown value="false" /> + <are-modules-shown value="false" /> + <flatten-packages value="false" /> + <is-autoscroll-to-source value="true" /> + </todo-panel> + <todo-panel id="all"> + <are-packages-shown value="true" /> + <are-modules-shown value="false" /> + <flatten-packages value="false" /> + <is-autoscroll-to-source value="true" /> + </todo-panel> + <todo-panel id="default-changelist"> + <are-packages-shown value="false" /> + <are-modules-shown value="false" /> + <flatten-packages value="false" /> + <is-autoscroll-to-source value="false" /> + </todo-panel> + </component> + <component name="ToolWindowManager"> + <frame x="15" y="22" width="1280" height="774" extended-state="0" /> + <editor active="true" /> + <layout> + <window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.23734178" sideWeight="0.0" order="7" side_tool="false" /> + <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> + <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" /> + <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Dataflow to this" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4129747" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" /> + <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" /> + <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" /> + <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" /> + <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24675325" sideWeight="0.75158226" order="0" side_tool="false" /> + <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Web Preview" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" /> + <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" /> + <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32911393" sideWeight="0.5" order="2" side_tool="false" /> + <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" /> + <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" /> + <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" /> + </layout> + </component> + <component name="VcsManagerConfiguration"> + <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" /> + <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" /> + <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" /> + <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" /> + <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" /> + <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" /> + <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" /> + <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> + <option name="LAST_COMMIT_MESSAGE" /> + <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" /> + <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" /> + <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" /> + <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" /> + <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" /> + <option name="ACTIVE_VCS_NAME" /> + <option name="UPDATE_GROUP_BY_PACKAGES" value="false" /> + <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" /> + <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> + <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" /> + </component> + <component name="VssConfiguration"> + <option name="CLIENT_PATH" value="" /> + <option name="SRCSAFEINI_PATH" value="" /> + <option name="USER_NAME" value="" /> + <option name="PWD" value="" /> + <CheckoutOptions> + <option name="COMMENT" value="" /> + <option name="DO_NOT_GET_LATEST_VERSION" value="false" /> + <option name="REPLACE_WRITABLE" value="false" /> + <option name="RECURSIVE" value="false" /> + </CheckoutOptions> + <CheckinOptions> + <option name="COMMENT" value="" /> + <option name="KEEP_CHECKED_OUT" value="false" /> + <option name="RECURSIVE" value="false" /> + </CheckinOptions> + <AddOptions> + <option name="STORE_ONLY_LATEST_VERSION" value="false" /> + <option name="CHECK_OUT_IMMEDIATELY" value="false" /> + </AddOptions> + <UndocheckoutOptions> + <option name="MAKE_WRITABLE" value="false" /> + <option name="REPLACE_LOCAL_COPY" value="2" /> + <option name="RECURSIVE" value="false" /> + </UndocheckoutOptions> + <GetOptions> + <option name="REPLACE_WRITABLE" value="0" /> + <option name="MAKE_WRITABLE" value="false" /> + <option name="ANSWER_NEGATIVELY" value="false" /> + <option name="ANSWER_POSITIVELY" value="false" /> + <option name="RECURSIVE" value="false" /> + <option name="VERSION" /> + </GetOptions> + </component> + <component name="XDebuggerManager"> + <breakpoint-manager /> + </component> + <component name="XPathView.XPathProjectComponent"> + <history /> + <find-history /> + </component> + <component name="antWorkspaceConfiguration"> + <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> + <option name="FILTER_TARGETS" value="false" /> + </component> + <component name="editorHistoryManager"> + <entry file="file:///home/sfraser/NetBeansProjects/ClojureLife/src/org/frasers/life/MultiThreadedLife.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="5" column="12" selection-start="0" selection-end="8693" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="file://$PROJECT_DIR$/src/org/frasers/life/MultiThreadedLife.clj"> + <provider selected="true" editor-type-id="text-editor"> + <state line="101" column="61" selection-start="4680" selection-end="4680" vertical-scroll-proportion="0.025423728"> + <folding /> + </state> + </provider> + </entry> + </component> + <component name="masterDetails"> + <option name="states"> + <map> + <entry key="Copyright.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl /> + </option> + </UIState> + </value> + </entry> + <entry key="Errors.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl /> + </option> + </UIState> + </value> + </entry> + <entry key="ProjectJDKs.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl> + <option name="proportions"> + <list> + <option value="0.2" /> + </list> + </option> + </SplitterProportionsDataImpl> + </option> + </UIState> + </value> + </entry> + <entry key="ScopeChooserConfigurable.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl /> + </option> + </UIState> + </value> + </entry> + </map> + </option> + <option name="myStates"> + <map> + <entry key="Copyright.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl /> + </option> + </UIState> + </value> + </entry> + <entry key="Errors.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl /> + </option> + </UIState> + </value> + </entry> + <entry key="ProjectJDKs.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl> + <option name="proportions"> + <list> + <option value="0.2" /> + </list> + </option> + </SplitterProportionsDataImpl> + </option> + </UIState> + </value> + </entry> + <entry key="ScopeChooserConfigurable.UI"> + <value> + <UIState> + <option name="proportions"> + <SplitterProportionsDataImpl /> + </option> + </UIState> + </value> + </entry> + </map> + </option> + </component> +</project> + diff --git a/lib/clojure.jar b/lib/clojure.jar new file mode 100644 index 0000000..5779050 Binary files /dev/null and b/lib/clojure.jar differ diff --git a/src/org/frasers/life/MultiThreadedLife.clj b/src/org/frasers/life/MultiThreadedLife.clj new file mode 100644 index 0000000..52b6035 --- /dev/null +++ b/src/org/frasers/life/MultiThreadedLife.clj @@ -0,0 +1,196 @@ +(comment + ; Parallelized Conway's Game of Life + ; Clojure implementation of "Conway's Game of Life" showing parallelization of the work. + ; See 'http://groups.google.com/group/clojure/msg/73df9c3446bf092f for background. + ; See 'http://www.youtube.com/watch?v=CFCYVfApPUc for an example run + ) + +(ns org.frasers.life.MultiThreadedLife + (:gen-class)) + +(import '(javax.swing JFrame JPanel JButton) + '(java.awt BorderLayout Dimension Color) + '(java.awt.event ActionListener)) + +; Used across all threads to signal if we are running or not +; Toggled by the Start/Stop buttons +(def running (atom false)) + +; Dimensions of the grid - make this bigger if you have more horsepower! +(def x-cells ( * 32 3)) +(def y-cells ( * 48 3)) +;(def x-cells 32) +;(def y-cells 32) + +; sequence of all the valid coordinates +(def range-cells (for [x (range x-cells) y (range y-cells)] [x y])) + + +; Size in pixels of the squares we will paint on the screen - make this smaller with larger size grids +(def cell-size 5) +; Optional Thread sleep factor to slow simulation down - I usually don't use it +(def life-delay 0) +; Used when we randomly populate the grid at startup +(def life-initial-prob 3) + +; example of how to set available-procs based on numner of processors JVM has access to. +; Not using this root level binding right now because we are passing in the number +; +;(def available-procs (.. java.lang.Runtime getRuntime availableProcessors)) +;(def available-procs 8) +;(def available-procs) +;(def batch-sets (for [cpu (range available-procs)] (take-nth available-procs (drop cpu range-cells)))) +;(def batch-sets) + +(defn calc-state) +(defn determine-initial-state) +(defn paint-cells) +(defn toggle-thread) + +; some things we will use to give each thread a different color +(def counter (ref 0)) +(def color-list [Color/RED Color/BLUE Color/GREEN Color/YELLOW Color/ORANGE Color/MAGENTA Color/PINK Color/CYAN]) +(def num-colors (count color-list)) +(def empty-color Color/BLACK) +(defn next-color) + +(defn -main[arg-num-threads] + + ; Example of setting number of threads based on the number of processors the JVM can see + ;(def num-threads (.. java.lang.Runtime getRuntime availableProcessors)) + (def num-threads (Integer/parseInt arg-num-threads)) + + ; Create a list of [x y] coordinates, one for each "thread" so that everyone has a unique + ; set of cells to work on + (def initial-batch-sets (for [offset (range num-threads)] (take-nth num-threads (drop offset range-cells)))) + + ; First we need to calculate the initial state that all the windows will start with + ; easiest way is to have one map of cell states that all windows initially point to + ; so we create an initial-state ref + ; and then set up a list of vectors: [threadNumber initialState] + (let [initial-state (ref {}) + initial-states-and-numprocs + (for [i (range num-threads)] [(inc i) (ref (into {} @initial-state))])] + + ; this is where we calculate the initial state of the first window + ; since all windows are initially pointing at the same map, everyone will + ; start up with the same state + (calc-state determine-initial-state initial-state initial-batch-sets next-color) + + ; make a list of vectors of [panel procs cell-state precalced-batch-sets] + ; we give each window 1, then 2, then 3... etc "threads" so the "precalced-batch-sets" are different + ; sized for each window + (def panels-and-state (for [[threadNumber cell-state] initial-states-and-numprocs] + [(proxy [JPanel] [] (paint [graphics] (paint-cells graphics cell-state))) + threadNumber + cell-state + ; since each window has a different set of threads, we calculate a "batch set" sized right for this window + ; so for the 1 thread window there will be one big batch with all cells listed + ; for a 2 thread window we will have 2 sets of cells listed + (for [offset (range threadNumber)] (take-nth threadNumber (drop offset range-cells))) + ]))) + + ; now we loop through the panels-and-state and materialize each one as a Swing JFrame + ; @param panel JPanel with a threadNumber and current set of cell-state + ; @param procs number of processes to use for this panel + ; @param cell-state current cell-state for this panel + ; @param batch-set set of [x y] coordinates, one batch for each thread of the panel + (doseq [[panel procs cell-state batch-set] panels-and-state] + + (let [f (JFrame. (format "Life - %s %s" procs (if (= procs 1) "Thread" "Threads" ))) + b (JButton. "Start")] + + (doto f + (.setLayout (BorderLayout.)) + (.setLocation 100 100) + (.setPreferredSize (Dimension. (* cell-size x-cells) (+ 60 (* cell-size y-cells)))) + (.add b BorderLayout/SOUTH) + (.add panel BorderLayout/CENTER) + (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) + (.pack) + (.setVisible true)) + + (. b addActionListener + (proxy [ActionListener] [] + (actionPerformed [evt] + (reset! running (false? @running)) + (. b (setText (if @running "Start" "Stop"))) + (doseq [[panel procs cell-state batch-set] panels-and-state] (toggle-thread panel cell-state batch-set procs))))))) + ) + +(defn next-color [] + (dosync (if (or (= @counter (dec num-colors)) (= @counter (dec num-threads))) + (ref-set counter 0) + (alter counter inc)))) + +(defn determine-initial-state [x y _] + (= 0 (rand-int life-initial-prob))) + +; I am here - would be interesting to eliminate all those derefs!!! (implicit in the map lookups!) +(defn determine-new-state [x y mycells] + (let [alive (count (for [dx [-1 0 1] dy [-1 0 1] + :when (and (not (= 0 dx dy)) + (not (= empty-color (mycells [ (mod (+ x dx) x-cells) (mod (+ y dy) y-cells)]))))] + :alive))] + (if (not (= (mycells [x y]) empty-color)) + (< 1 alive 4) + (= alive 3)))) + +; replaced this with a single threaded reduce in calc-state +;(defn update-batch-of-new-cells [new-cells list-of-batches] +; (dosync +; ; first here is the vector of [x y], and second is the state +; (dorun (map #(commute new-cells assoc (first %) (second %)) +; list-of-batches)))) + +(defn calc-batch-of-new-cell-states [cell-state batch-cells mycells next-color] + ( let [thread-color (nth color-list (next-color))] + doall (map + #(let [new-cell-state (if (cell-state (first %) (second %) mycells) thread-color empty-color)] + ;first here is the vector of [x y], and second is the state (color) + [[(first %) (second %)] new-cell-state]) + batch-cells))) + +; This is the all important function where parallelization kicks in +;(defn calc-state-old [cell-state mycells batch-set next-color] +; (let [new-cells (ref {})] +; (dorun (pmap #(update-batch-of-new-cells new-cells %) +; (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) +; batch-set))) +; (dosync (ref-set mycells @new-cells)))) + +; Gonna try and reduce shared state - instead we'll put the states into the +; batches and be done with it +(defn calc-state [cell-state mycells batch-set next-color] + (let [new-cells (doall (reduce into {} + ; This no longer seems to run faster with more threads? Why? Tried doall, no difference + ; note that pmap is lazy so maybe since this used to be pmap inside of pmap??? + (doall (pmap #(calc-batch-of-new-cell-states cell-state % mycells next-color) + batch-set))))] + (dosync (ref-set mycells new-cells)))) + +; Type Hint here makes a huge performance difference for the better +(defn paint-cells [#^java.awt.Graphics graphics mycells] + (doseq [[[x,y] state] @mycells] + (doto graphics + (.setColor state) + (.fillRect (* cell-size x) (* cell-size y) cell-size cell-size)))) + +; This is what gets called when you hit the State/Stop button +(defn toggle-thread [panel mycells batch-set procs] + (if @running + (let [mycounter (ref 0) + next-color #(dosync (if (or (= @mycounter (dec num-colors)) (= @mycounter (dec procs))) + (ref-set mycounter 0) + (alter mycounter inc)))] + (do + (. (Thread. + #(loop [] + (calc-state determine-new-state mycells batch-set next-color) + (.repaint panel) + ;(if life-delay (Thread/sleep life-delay)) + (if @running (recur)))) + start))))) + + +(-main "3")
cagatay/Evolution-9
dee5b0d95d722706d5014595d4e7d18ef81929cd
Fixed grade values at GUI
diff --git a/src/main.py b/src/main.py index b94d70c..3ad2a83 100755 --- a/src/main.py +++ b/src/main.py @@ -1,272 +1,266 @@ + #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from mingus.midi import fluidsynth from util.storage import db from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), - 'play' : self.builder.get_object('play_button'), - 'get_generation' : self.builder.get_object('get_generation_button') + 'play' : self.builder.get_object('play_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') else: self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: - self.controls['get_generation'].set_sensitive(True) if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluate': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] + fixed_grade = "%.5f" % ( individual.grade ) self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) - self.builder.get_object('grade_label').set_text(str(individual.grade)) + self.builder.get_object('grade_label').set_text( fixed_grade ) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return - def update_genome_list(self, l = None): + def update_genome_list(self): self.genome_list.clear() - if l is None: - l = self.evolution9.current_generation + l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return - def on_get_generation_button_clicked(self, *args): - generation = int(self.builder.get_object('get_generation_entry').get_text()) - self.evolution9.get_generation(generation) - self.update_genome_list(self.evolution9.searched_generation) - self.error_message('working') - def on_step_50_button_clicked(self, *args): if not self.evolution9.initialized: self.evolution9.initialize() if self.evolution9.state == 'evaluate': self.evolution9.evaluate(self.log_console) if self.evolution9.state == 'select': self.evolution9.apply_selection(self.log_console) for _ in range(50): self.evolution9.reproduce(self.log_console) self.evolution9.evaluate(self.log_console) self.evolution9.apply_selection(self.log_console) self.update_state() self.update_genome_list() self.update_generation_info() return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() self.update_generation_info() return def update_generation_info(self): - max_grade = str(self.evolution9.max_grade) - min_grade = str(self.evolution9.min_grade) - avg_grade = str(self.evolution9.avg_grade) + + max_grade = "%.5f" % ( self.evolution9.max_grade ) + min_grade = "%.5f" % ( self.evolution9.min_grade ) + avg_grade = "%.5f" % ( self.evolution9.avg_grade ) self.builder.get_object('max_grade_label').set_text(max_grade) self.builder.get_object('min_grade_label').set_text(min_grade) self.builder.get_object('average_grade_label').set_text(avg_grade) def reproduce(self, *args): self.evolution9.reproduce(self.log_console) self.update_state() self.update_genome_list() def on_initialize_button_clicked(self, *args): if self.evolution9.initialized: self.reproduce(*args) else: self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() def on_play_button_clicked(self, *args): index = self.genome_view.get_selection().get_selected()[1] index = self.genome_list.get_path(index)[0] fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 7f152d2..ba85fca 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,1054 +1,1053 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_step_50_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHBox" id="hbox4"> <property name="visible">True</property> <child> <object class="GtkEntry" id="get_generation_entry"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="get_generation_button"> <property name="label" translatable="yes">Get generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_get_generation_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">2</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label22"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Selected</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="selected_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> <property name="y_options">GTK_FILL</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_play_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkTable" id="table4"> <property name="visible">True</property> <property name="n_rows">3</property> <property name="n_columns">2</property> <property name="homogeneous">True</property> <child> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Max. grade:</property> </object> <packing> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="max_grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label_min"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Min. grade</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="min_grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Average grade:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="average_grade_label"> <property name="visible">True</property> + <property name="xalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> - <property name="yalign">2.2351741291171123e-10</property> + <property name="yalign">2.2351741291171123e-010</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="has_frame">False</property> - <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="open_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Open evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox4"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkComboBox" id="evolution_combo"> <property name="visible">True</property> <property name="active">0</property> - <property name="entry_text_column">0</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area4"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="open_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">open_evolution_ok_button</action-widget> </action-widgets> </object> </interface>
cagatay/Evolution-9
f22ca3df2bb8b23d60b83c8472f5298dc03b12ba
added samples from a family
diff --git a/samples/evolution9-51-0.mid b/samples/evolution9-51-0.mid new file mode 100644 index 0000000..e1a3883 Binary files /dev/null and b/samples/evolution9-51-0.mid differ diff --git a/samples/evolution9-51-1.mid b/samples/evolution9-51-1.mid new file mode 100644 index 0000000..cc46a88 Binary files /dev/null and b/samples/evolution9-51-1.mid differ diff --git a/samples/evolution9-51-2.mid b/samples/evolution9-51-2.mid new file mode 100644 index 0000000..ea2a068 Binary files /dev/null and b/samples/evolution9-51-2.mid differ diff --git a/samples/evolution9-51-5.mid b/samples/evolution9-51-5.mid new file mode 100644 index 0000000..3cb7815 Binary files /dev/null and b/samples/evolution9-51-5.mid differ diff --git a/samples/evolution9-51-7.mid b/samples/evolution9-51-7.mid new file mode 100644 index 0000000..6faf1ee Binary files /dev/null and b/samples/evolution9-51-7.mid differ
cagatay/Evolution-9
8e0ed10c36462ac8e7e97cd673d2ee70d27bb30c
are you kidding me?
diff --git a/README.txt b/README.txt index 4103170..bc0c122 100644 --- a/README.txt +++ b/README.txt @@ -1,12 +1,12 @@ requirements: - python 2.6 (strictly) - pybrain (and its own requirements) - mingus - pyevolve + python 2.6 (strictly) + pybrain (and its own requirements) + mingus + pyevolve pygtk installation: python 2.6 http://www.python.org/download pybrain http://pybrain.org/pages/download (make sure that you installed SciPy and Numpy) mingus http://code.google.com/p/mingus/downloads/list pyevolve http://pyevolve.sourceforge.net/intro.html#downloads
cagatay/Evolution-9
15b386344bf83f1caf05095eaaab7c76196d91f6
the final commit
diff --git a/src/brain/NN.py b/src/brain/NN.py index e844cac..5202f81 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,86 +1,88 @@ from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet from pybrain.tools.shortcuts import buildNetwork import constants import pickle import math from pybrain.auxiliary import GradientDescent from pybrain.structure import RecurrentNetwork, LinearLayer, SigmoidLayer, FullConnection import random from util import rttl import math class neural_network(object): def __init__(self, name, dataset, trained, store): self.name = name self.store = store self.trained = trained self.dataset = dataset - ''' self.net = RecurrentNetwork() self.net.addInputModule(LinearLayer(2, name='in')) self.net.addModule(SigmoidLayer(3, name='hidden')) self.net.addOutputModule(LinearLayer(2, name='out')) self.net.addConnection(FullConnection(self.net['in'], self.net['out'], name='c1')) self.net.addConnection(FullConnection(self.net['hidden'], self.net['out'], name='c2')) self.net.addRecurrentConnection(FullConnection(self.net['hidden'], self.net['hidden'], name='c3')) self.net.sortModules() ''' self.net = buildNetwork(2, 3, 2) - + ''' if not self.trained: self.train() return def save(self): self.store.save_neural_network(self.name, self.dataset, self.trained) return @classmethod def get_saved(cls, name, store): result = store.get_neural_network(name) return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() - + print result return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) store.new_neural_network(name, dataset) return def evaluate(self, genome): err = 0.0 for i in range(len(genome) - 1): + print '---------- input ------------' + print genome[i] output = self.net.activate(genome[i]) + print '--------- output ------------' + print output target = genome[i + 1] err += (math.fabs(output[0] - target[0]) + math.fabs(output[1] - target[1])) return 1/err def train(self): ds_store = [] for song in self.dataset: ds_in = song[:len(song) - 1] ds_out = song[1:] ds = SupervisedDataSet(2, 2) for i in range(len(song) -1): - if ds_in[i] not in ds_store: - ds.addSample(ds_in[i], ds_out[i]) - ds_store.append(ds_in[i]) + #if ds_in[i] not in ds_store: + ds.addSample(ds_in[i], ds_out[i]) + ds_store.append(ds_in[i]) if len(ds): trainer = BackpropTrainer(self.net, ds, verbose=True) - for _ in range(10): - trainer.train() + trainer.trainUntilConvergence() self.save() diff --git a/src/evolution/manager.py b/src/evolution/manager.py index e1bac62..8e6b7d3 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,196 +1,206 @@ from brain.NN import neural_network from evolution import operators from evolution.genome import song class evolution(object): def __init__(self, name, evaluator, population_size, store, generation_count = 0, state='uninitialized'): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = generation_count self.state = state if self.state != 'uninitialized': self.get_current_generation() else: self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, self.state) return def save_genomes(self): for g in self.current_generation: self.store.save_genome(g.name, g.genome, g.evolution, g.generation, g.individual_id, g.parent_1, g.parent_2, g.grade, g.status) return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) return cls(result[0], result[3], result[1], store, result[2], result[4]) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None def initialize(self, console = None): self.current_generation = [] for i in xrange(self.population_size): g = song(operators.random_genome(), self.name, 0, i) self.current_generation.append(g) self.state = 'evaluate' self.save_genomes() self.save() if console: console('%s is initialized'%self.name) return @property def initialized(self): return self.state != 'uninitialized' def get_current_generation(self): result = self.store.get_genomes(self.name, self.generation_count) if result: self.current_generation = [] for i in result: g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) self.current_generation.append(g) return + def get_generation(self, generation): + result = self.store.get_genomes(self.name, generation) + + if result: + self.searched_generation = [] + + for i in result: + g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) + self.searched_generation.append(g) + def evaluate(self, console = None): self.results = [] for g in self.current_generation: result = self.evaluator.evaluate(g.int_list) g.grade = result if console: console('%s evaluation result: %f'%(g.name, result)) self.current_generation = sorted(self.current_generation, key=lambda x: x.grade, reverse=True) self.max_grade = self.current_generation[0].grade self.min_grade = self.current_generation[len(self.current_generation) - 1].grade self.avg_grade = sum([x.grade for x in self.current_generation])/self.population_size for i in range(self.population_size): if i < self.population_size/2: self.current_generation[i].status = 'selected' else: self.current_generation[i].status = 'eliminated' self.state = 'select' if console: console('Generation %d of %s : evaluation complete'%(self.generation_count, self.name)) return def apply_selection(self, console = None): self.save_genomes() self.current_generation = self.current_generation[:self.population_size/2] self.state = 'reproduce' self.save() console('%s : applied selection on generation %d'%(self.name, self.generation_count)) return def reproduce(self, console = None): self.generation_count += 1 console('%s : reproducing of generation %d started'%(self.name, self.generation_count)) pool = [] index = 0 while self.current_generation: l = len(self.current_generation) - 1 if not l: break a = operators.r(l) parent_1 = self.current_generation[a] del self.current_generation[a] a = operators.r(l - 1) parent_2 = self.current_generation[a] del self.current_generation[a] child_1_g, child_2_g = operators.random_crossover(parent_1.note_list, parent_2.note_list) operators.random_mutator(child_1_g) operators.random_mutator(child_2_g) parent_1.individual_id = index parent_1.status = 'created' parent_1.generation = self.generation_count parent_1.grade = 0.0 index += 1 parent_2.individual_id = index parent_2.status = 'created' parent_2.generation = self.generation_count parent_2.grade = 0.0 index += 1 child_1 = song(child_1_g, self.name, self.generation_count, index, parent_1.name, parent_2.name) index += 1 child_2 = song(child_2_g, self.name, self.generation_count, index, parent_1.name, parent_2.name) index += 1 t = parent_1.note_list operators.random_mutator(t) parent_1.set_genome(t) t = parent_2.note_list operators.random_mutator(t) parent_2.set_genome(t) pool += [parent_1, parent_2, child_1, child_2] console('created %s and %s from %s and %s'%(child_1.name, child_2.name, parent_1.name, parent_2.name)) self.current_generation = pool self.save() self.save_genomes() self.state = 'evaluate' console('%s : created generation %d'%(self.name, self.generation_count)) diff --git a/src/main.py b/src/main.py index a24c0d8..b94d70c 100755 --- a/src/main.py +++ b/src/main.py @@ -1,263 +1,272 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from mingus.midi import fluidsynth from util.storage import db from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), - 'play' : self.builder.get_object('play_button') + 'play' : self.builder.get_object('play_button'), + 'get_generation' : self.builder.get_object('get_generation_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') else: self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: + self.controls['get_generation'].set_sensitive(True) if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluate': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return - def update_genome_list(self): + def update_genome_list(self, l = None): self.genome_list.clear() - l = self.evolution9.current_generation + if l is None: + l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return + def on_get_generation_button_clicked(self, *args): + generation = int(self.builder.get_object('get_generation_entry').get_text()) + self.evolution9.get_generation(generation) + self.update_genome_list(self.evolution9.searched_generation) + self.error_message('working') + def on_step_50_button_clicked(self, *args): if not self.evolution9.initialized: self.evolution9.initialize() if self.evolution9.state == 'evaluate': self.evolution9.evaluate(self.log_console) if self.evolution9.state == 'select': self.evolution9.apply_selection(self.log_console) for _ in range(50): self.evolution9.reproduce(self.log_console) self.evolution9.evaluate(self.log_console) self.evolution9.apply_selection(self.log_console) self.update_state() self.update_genome_list() self.update_generation_info() return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() self.update_generation_info() return def update_generation_info(self): max_grade = str(self.evolution9.max_grade) min_grade = str(self.evolution9.min_grade) avg_grade = str(self.evolution9.avg_grade) self.builder.get_object('max_grade_label').set_text(max_grade) self.builder.get_object('min_grade_label').set_text(min_grade) self.builder.get_object('average_grade_label').set_text(avg_grade) def reproduce(self, *args): self.evolution9.reproduce(self.log_console) self.update_state() self.update_genome_list() def on_initialize_button_clicked(self, *args): if self.evolution9.initialized: self.reproduce(*args) else: self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() def on_play_button_clicked(self, *args): index = self.genome_view.get_selection().get_selected()[1] index = self.genome_list.get_path(index)[0] fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 9047630..7f152d2 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,1016 +1,1054 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> + <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_step_50_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> + <child> + <object class="GtkHBox" id="hbox4"> + <property name="visible">True</property> + <child> + <object class="GtkEntry" id="get_generation_entry"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="invisible_char">&#x2022;</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="get_generation_button"> + <property name="label" translatable="yes">Get generation</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_get_generation_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">1</property> + </packing> + </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> - <property name="position">1</property> + <property name="position">2</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label22"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Selected</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="selected_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> <property name="y_options">GTK_FILL</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_play_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkTable" id="table4"> <property name="visible">True</property> <property name="n_rows">3</property> <property name="n_columns">2</property> + <property name="homogeneous">True</property> <child> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Max. grade:</property> </object> <packing> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="max_grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label_min"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Min. grade</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="min_grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Average grade:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="average_grade_label"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> <property name="y_options">GTK_FILL</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> - <property name="active">0</property> + <property name="has_frame">False</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="open_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Open evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox4"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkComboBox" id="evolution_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area4"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="open_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">open_evolution_ok_button</action-widget> </action-widgets> </object> </interface> diff --git a/src/util/music.py b/src/util/music.py index df1453c..fca9bc5 100644 --- a/src/util/music.py +++ b/src/util/music.py @@ -1,30 +1,30 @@ import random from mingus.containers.Note import Note note_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] class note(object): def __init__(self, note, octave, duration): self.note = str(note) self.octave = '' if octave is None else octave self.duration = duration self.mingus_duration = int(duration) if self.note == 'P': self.mingus_note = None else: self.mingus_note = Note(self.note, int(self.octave)) def int_tuple(self): - return (int(self.mingus_note) if self.mingus_note else 0, self.mingus_duration) + return (float(int(self.mingus_note))/1000 if self.mingus_note else 1, -1*float(self.mingus_duration)/1000) def __str__(self): return self.duration + self.note + self.octave def random_note(): return note(random.choice(note_range), random.choice(octave_range), random.choice(duration_range))
cagatay/Evolution-9
455a31a3cd88c68c15b665bded3dfffb702599a9
latest
diff --git a/input/beatles.txt b/input/beatles.txt index 16d1f6b..bcbb4d5 100644 --- a/input/beatles.txt +++ b/input/beatles.txt @@ -1,14 +1,31 @@ hardday:d=4,o=5,b=180:8c#,8d,8c#,e,p,e,8p,e,p,8e,8e,8d,8e,g,p,8e,8d,8e,c#,p,8c#,8d,8c#,e,p,e,8p,e,p,8e,8e,8d,8e,g,p,8e,8d,8e,c# Love:d=8,o=6,b=180:d,d,d,d,4d,2p,d,d,d,d,4d,2p,d,d,d#,4e,p,4b5,2p,a5,b5,a5,g5,4g5 Chance:d=4,o=6,b=180:e,d,c,d,g5,2p,g5,f,e,d,c,p,e,d,c,d,g5,2p,g5,f,e,d,c Help:d=8,o=5,b=125:b,b,b,b,b,b,b,4b,4b,b,b,d6,b,a,p,4g,4p,4a#,4b,4a,4b,4b,a#,b,b,b,c6,c6,c6,c6,b,p jude:d=8,o=5,b=180:g,e,p,e,e,g,a,d,p,p,d,e,f,c,c,c,b,g,a,g,f,4e,p,g,a,a,a,d6,c6,b,b,c6,a,4g,c,d,e,a,a,4g Madonna:d=8,o=6,b=100:e,4e,16d5,d,16p,16c,4p,e,e,d,16a5,4c,4p,e,e,g,e,a,g,e,4c,p,c,d5,c,2p,e,4e,16d5,d,16p,16c,4p,e,e,d,16a5,4c letitbe:d=4,o=5,b=112:16g.,8g,g,8g,a,8e,8g,g.,8c6,d.6,e6,8e6,e6,8d6,8d6,8c6,2c6,e6,8e6,f6,8e6,8e6,d.6,8e6,8d6,2c6 do:d=4,o=6,b=180:d,d,8f,g,p,8f,8d,8d,8f,g,p,8f,8d,8d,8f,g,8p,d,e,d,c,e,p,g5,g5,a#5,g5 you:d=8,o=6,b=180:d,e,g,4g,f#,e,p,p,d,e,g,g,f#,e,p,p,d,e,g,4g,p,4f,4p,4e Fields:d=8,o=5,b=180:b,b,c6,b,g,d,e,a,g,f,f,g,a,d,p,2p,4f,4g,4g#,d,d6,c6,b,a,g#,a,4b,p,b,g,e,p,b,g,d,a,4g Hand:d=8,o=6,b=180:g,a,g,p,p,f,4e,p,e,g,f,e,d,p,4e,e,e,e,e,b,p Four:d=8,o=6,b=180:e5,d#5,e5,g5,e5,g5,a5,g5,4c,c,e,c,a5,4d,2p,b5,c,c#,d,b5,c,c#,d,b5,a#5,a5,4a5,4p,4b5,4c,4c#,4d,4e,4d#,d,c,p Submarine:d=8,o=5,b=180:4d6,4d6,4d6,d6,e6,a,a,a,a,4a,a,a,a,a,4a,p,g,g,g,g,4g -yday:d=4,o=5,b=125:g,8f,f,p,8a,8b,8c#6,8d6,e6,8p,8f6,e6,8d6,d6,p,8d6,8d6,8c6,8a#,8a,8g,8a#,8a,8a,a,8p,g,f,8a,8g,g,8p,8d,f,8p,8a,a \ No newline at end of file +yday:d=4,o=5,b=125:g,8f,f,p,8a,8b,8c#6,8d6,e6,8p,8f6,e6,8d6,d6,p,8d6,8d6,8c6,8a#,8a,8g,8a#,8a,8a,a,8p,g,f,8a,8g,g,8p,8d,f,8p,8a,a +amlife:d=32,o=5,b=100:2a,8c6,8b,8a,g,2e.,8p,a,8a,8a,8c6,8b,8a,g,2e,8p,e,2d,8f,8e,8d,e,2g,8p,e,2d,8f,8e,8d,e,2g,8p,p,2a,8c6,8b,8a,g,2e.,8p,a,8a,8a,8c6,8b,8a,g,2e,8p,e,2d,8f,8e,8d,e,2g,8p,e,2d,8f,8e,8d,e,2g,8p,p +americanpie:d=4,o=5,b=125:8d#,8d#,8d#,8f,8d#,p,2d#,c#,8c#,8c#,8c,8a#4,8g#4,a#4,d#,8d#,8d#,8d#,8d#,8c,8c#,8c#,8c#,8c#,8c,8a#4,8g#4,8d#4,p,8p,8d#,8d#,8f,8p,8c#,8p,8c#,8c#,8c#,8c,8a#4,8g#4,8a#4,p,8c,8a#4,8g#4,8f4,8g#4,16f4,8g#.4,8g4,f4,2a#4 +beautifulstranger:d=4,o=5,b=125:8d#,8c#,8b4,1c#,8d#,8c#,8b4,16c#,16p,8c#,8d#,8c,1g#4,8d#,8c#,8b4,c#,8g#.4,16p,1g#4,8d#,8c#,8b4,8c#.,16p,8d#.,16p,8d#.,16p,1c#,8p,8c#,8f,g#,8f#,8f,8f#,f,1c#,8p,8c#,8f,g#,8f#,8f,8f#,f,8d#,8c#,8b4,1c# +Cherish:d=8,o=6,b=160:f,p,e,p,g5,p,4a5,p,c,16c,10p,c,d,10p,16c,5p,e,p,f,p,g,p,4d,p,b5,16b5,5p,b5,32p,c +Dieanother:d=4,o=5,b=200:c6,p,d#6,2d6,a#,p,a#,2p,d#.6,8p,d.6,8p,c6,p,c6,p,d#6,d6,p,a#.,2p,p,8p,d#.6,8p,d.6,8p,c6,p,c6,p,d#6,d6,p,a#.,2p,p,8p,d#6,p,2d6,c6,p,c6,p,d#6,d6,p,a#.,p,8p,a#,p,d#6,d.6,8p,c6,2p,p,8d#6,p,8p,8f6,2p,8p,2f6,2p,8d#.6,16p,f6,8d#.6,16p,2f6,2p,8d#6,p,8p,8f6,2p,8p,2f6,2p,8d#.6,16p,f6,8d#.6 +Me:d=4,o=5,b=180:e,e,e,e,f,g,a,g,g,g,a,a,g,8c6,8g,8p,f,e,8p,8e,8f,8g,8d,8d,d,e,f,c,c,8p,8c,8d,8c,8e,8g +express:d=4,o=5,b=112:a,8a,g,a,8f,f,f,g,8f,8g,g,a,8b,g,8f,8f,8f,8f,8g,8a,8g,p,a,8a,g,a,8f,8f,f,8f,8f,8f,8f,8g,8g,8f,a,8b,g. +Fever:d=8,o=6,b=140:d,32p,c,d,32p,c,d,p,a5,32p,4c,4d,2p,d,32p,c,d,32p,c,d,32p,c,a5,32p,4a5,4p,d,32p,c,d,32p,c,d,p,a5,32p,4c,d,2p,a5,a5,p,d,32p,c,d,32p,c,d,32p,c,a5,32p,16a5,5p,a5,16a5,10p,a5,4c,16a +Hollywood:d=4,o=5,b=125:8d6,8e6,g6,e6,16g,16p,8p,16g,16p,8p,16c,16p,8p,16c,16p,8p,16a,16p,8e6,8d6,8e6,8b6,8a6,g6,8e6,d.6,16c,16p,8p,16c,16p,8p,16a,16p,8p,8d6,8e6,g6,e6,16g,16p,d.6,8b,8a,16c,16p,8p,16a,16p,8e6,8d6,8e6,8b6,8a6,8g6,8e6,16g,16p,8p,16g,16p,8p,16c,16p,8p,16c,16p,8p,16a,16p,8p,16a,16p,8p,8g +hungup:d=8,o=5,b=125:g,a,2a.,p,a,4c6,b,g,g,a,4a,4a,a,a,p,2g.,p,4a,g,f,g,f,p,g,p,f,p,2d,p,4a,g,g,p,2f.,p,4g,4g,1d,2p,4g,4g,1d,2p,4g,4g,1d,2p,4g,4g,1d +LAISLA:d=4,o=5,b=200:c#.,g#.4,c#,d#.,g#.4,d#,8e.,d#,2e,2p,2e,2e,2g#,g#,8e,e.,g#,f#.,8e,2d#,c#.,g#.4,c#,d#.,d#.,f#,8e,d#,2e,2p,2e,2e,f#,g#,g#,8e,e.,g#,f#,d#,2d#,p,e,8e,e,e,e,8d#,2d#.,f#,8f#,f#,f#,f#,e,2e.,8d#,d#,d#,e,d#,c#,2c#,8c#,c#,c#.,d#,8e,d#,2e +Virgin:d=8,o=5,b=180:c,d,f,d,p,p,g,g,f,g,g,c6,a,p,p,c,d,a,g,f,g,d,4d,p,f,g,f,d +luvprofu:d=4,o=5,b=125:8e,8e,8e,2f,8p,8e,8p,e,f.,8p,8e,8e,8e,2e,8p,8e,8e,8e,2e,8p,8e,8e,8e,2f,8p,8e,8p,e,f.,8p,8e,8e,8e,2e,8p,8e,8e,8e,16e,16d,c.,8p,8e,8e,8e,2e,8p,8e,8e,8d +MUSIC:d=4,o=5,b=125:d6,8a#,8c6,8p,8c6,p,2p,8g,8g,8g,8g,d6,8a#,8c6,8p,8c6,p,2p,8g,8g,8g,8g,d6,8a#,8c6,8p,8c6,8p,c6,a#,g.,2p,d6,8c6,8a#,c6,a#,8c.6,16c6,8c6,8a#,g,8g,8a#,d6,8c6,8a#,c6,a#,2p,8p,8g,8g,8a#,d6,8a#,8c6,p,8p,8a,8c6,8d6,8c6,8a#,g,8g,8a#,d6,a#,c6,a# +preach:d=8,o=5,b=125:48a#.,10p,a#,a,p,g,2p,a#,4a,4f,g,g,2p,g,g,d6,d6,d6,4c6,4p,d6,4c6,4p,a#,c6,d6,4c6,4a# +Rain:d=8,o=5,b=100:1e6,p,e6,d6,c#6,b,b,a,4a,e6,d6,c#6,b,b,b,b,b,c#6,16a,16a,b,4a,p,1e +Girl:d=8,o=6,b=112:16a#5,c.,d#,2d#,p,4a#,g,4g#,4g.,16f,d#.,d#,2d#,p,16a#5,c.,d#,2d#,p,4a#,g,4g#,4g.,16f,d#.,d#,2d#,p,16a#5,c.,d#,2d diff --git a/src/brain/NN.py b/src/brain/NN.py index 8a812b5..e844cac 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,85 +1,86 @@ from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet from pybrain.tools.shortcuts import buildNetwork import constants import pickle import math from pybrain.auxiliary import GradientDescent from pybrain.structure import RecurrentNetwork, LinearLayer, SigmoidLayer, FullConnection import random from util import rttl import math class neural_network(object): def __init__(self, name, dataset, trained, store): self.name = name self.store = store self.trained = trained self.dataset = dataset ''' self.net = RecurrentNetwork() self.net.addInputModule(LinearLayer(2, name='in')) self.net.addModule(SigmoidLayer(3, name='hidden')) self.net.addOutputModule(LinearLayer(2, name='out')) self.net.addConnection(FullConnection(self.net['in'], self.net['out'], name='c1')) self.net.addConnection(FullConnection(self.net['hidden'], self.net['out'], name='c2')) self.net.addRecurrentConnection(FullConnection(self.net['hidden'], self.net['hidden'], name='c3')) self.net.sortModules() ''' self.net = buildNetwork(2, 3, 2) if not self.trained: self.train() return def save(self): self.store.save_neural_network(self.name, self.dataset, self.trained) return @classmethod def get_saved(cls, name, store): result = store.get_neural_network(name) return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) store.new_neural_network(name, dataset) return def evaluate(self, genome): err = 0.0 for i in range(len(genome) - 1): output = self.net.activate(genome[i]) target = genome[i + 1] err += (math.fabs(output[0] - target[0]) + math.fabs(output[1] - target[1])) return 1/err def train(self): ds_store = [] for song in self.dataset: ds_in = song[:len(song) - 1] ds_out = song[1:] ds = SupervisedDataSet(2, 2) for i in range(len(song) -1): if ds_in[i] not in ds_store: ds.addSample(ds_in[i], ds_out[i]) ds_store.append(ds_in[i]) if len(ds): trainer = BackpropTrainer(self.net, ds, verbose=True) - trainer.train() + for _ in range(10): + trainer.train() self.save() diff --git a/src/main.py b/src/main.py index fc15f36..a24c0d8 100755 --- a/src/main.py +++ b/src/main.py @@ -1,244 +1,263 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from mingus.midi import fluidsynth from util.storage import db from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), 'play' : self.builder.get_object('play_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') else: self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluate': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return + def on_step_50_button_clicked(self, *args): + if not self.evolution9.initialized: + self.evolution9.initialize() + if self.evolution9.state == 'evaluate': + self.evolution9.evaluate(self.log_console) + if self.evolution9.state == 'select': + self.evolution9.apply_selection(self.log_console) + + for _ in range(50): + self.evolution9.reproduce(self.log_console) + self.evolution9.evaluate(self.log_console) + self.evolution9.apply_selection(self.log_console) + + self.update_state() + self.update_genome_list() + self.update_generation_info() + + return + def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() self.update_generation_info() return def update_generation_info(self): max_grade = str(self.evolution9.max_grade) min_grade = str(self.evolution9.min_grade) avg_grade = str(self.evolution9.avg_grade) self.builder.get_object('max_grade_label').set_text(max_grade) self.builder.get_object('min_grade_label').set_text(min_grade) self.builder.get_object('average_grade_label').set_text(avg_grade) def reproduce(self, *args): self.evolution9.reproduce(self.log_console) self.update_state() self.update_genome_list() def on_initialize_button_clicked(self, *args): if self.evolution9.initialized: self.reproduce(*args) else: self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() def on_play_button_clicked(self, *args): index = self.genome_view.get_selection().get_selected()[1] index = self.genome_list.get_path(index)[0] fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 6439dfc..9047630 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,982 +1,989 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> + <signal name="clicked" handler="on_step_50_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label22"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Selected</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> + <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="selected_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> + <property name="y_options">GTK_FILL</property> </packing> </child> </object> <packing> + <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_play_button_clicked"/> </object> <packing> + <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> + <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkTable" id="table4"> <property name="visible">True</property> <property name="n_rows">3</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Max. grade:</property> </object> <packing> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="max_grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label_min"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Min. grade</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="min_grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Average grade:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="average_grade_label"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> - <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="expand">False</property> + <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="open_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Open evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox4"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkComboBox" id="evolution_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area4"> <property name="visible">True</property> <property name="layout_style">end</property> <child> diff --git a/src/util/music.py b/src/util/music.py index 581bd42..df1453c 100644 --- a/src/util/music.py +++ b/src/util/music.py @@ -1,34 +1,30 @@ import random from mingus.containers.Note import Note -from mingus.core import value note_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] -dot_range = ['.', ''] class note(object): - def __init__(self, note, octave, duration, dot): + def __init__(self, note, octave, duration): self.note = str(note) self.octave = '' if octave is None else octave self.duration = duration - self.dot = dot - self.mingus_duration = value.dots(int(self.duration), int(bool(self.dot))) + self.mingus_duration = int(duration) if self.note == 'P': self.mingus_note = None else: self.mingus_note = Note(self.note, int(self.octave)) def int_tuple(self): return (int(self.mingus_note) if self.mingus_note else 0, self.mingus_duration) def __str__(self): - return self.duration + self.note + self.dot + self.octave + return self.duration + self.note + self.octave def random_note(): return note(random.choice(note_range), random.choice(octave_range), - random.choice(duration_range), - random.choice(dot_range)) + random.choice(duration_range)) diff --git a/src/util/rttl.py b/src/util/rttl.py index f223ef0..b0dcfd1 100644 --- a/src/util/rttl.py +++ b/src/util/rttl.py @@ -1,64 +1,62 @@ ''' Created on 12 Ara 2010 @author: melih ''' from util.music import note def parse(rttl_string): rttl_string = rttl_string.strip() track = [] parts = rttl_string.split(":") defaults = parts[1] notes = parts[2] if defaults: defaults = defaults.split(",") defaultDuration = defaults[0].split("=")[1] defaultOctave = defaults[1].split("=")[1] notes = notes.split(",") for n in notes: n = n.strip().upper() if defaults: duration = defaultDuration octave = defaultOctave - dot = '' if n[0].isdigit(): if n[1].isdigit(): duration = n[:2] n = n[2:] else: duration = n[0] n = n[1:] if n[len(n) - 1].isdigit(): octave = n[len(n) - 1] n = n[0:len(n) - 1] if n.endswith("."): - dot = '.' n = n[0:len(n) - 1] - track.append(note(n, duration, octave, dot)) + track.append(note(n, octave, duration)) return track def dataset_from_file(file_uri): ds_file = file(file_uri) ds_list = [] for line in ds_file: track = parse(line) ds_list.append(to_int(track)) return ds_list def dump(note_list): out = '::' for note in note_list: out += str(note) + ',' return out.rstrip(',') def to_int(note_list): return [x.int_tuple() for x in note_list]
cagatay/Evolution-9
aa6f88fd0f32df94750e670b62371219e430dc97
latest
diff --git a/src/evolution/manager.py b/src/evolution/manager.py index bd546fc..e1bac62 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,191 +1,196 @@ from brain.NN import neural_network from evolution import operators from evolution.genome import song class evolution(object): def __init__(self, name, evaluator, population_size, store, generation_count = 0, state='uninitialized'): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = generation_count self.state = state if self.state != 'uninitialized': self.get_current_generation() else: self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, self.state) return def save_genomes(self): for g in self.current_generation: self.store.save_genome(g.name, g.genome, g.evolution, g.generation, g.individual_id, g.parent_1, g.parent_2, g.grade, g.status) return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) return cls(result[0], result[3], result[1], store, result[2], result[4]) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None def initialize(self, console = None): self.current_generation = [] for i in xrange(self.population_size): g = song(operators.random_genome(), self.name, 0, i) self.current_generation.append(g) self.state = 'evaluate' self.save_genomes() self.save() if console: console('%s is initialized'%self.name) return @property def initialized(self): return self.state != 'uninitialized' def get_current_generation(self): result = self.store.get_genomes(self.name, self.generation_count) if result: self.current_generation = [] for i in result: g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) self.current_generation.append(g) return def evaluate(self, console = None): self.results = [] for g in self.current_generation: result = self.evaluator.evaluate(g.int_list) g.grade = result if console: console('%s evaluation result: %f'%(g.name, result)) self.current_generation = sorted(self.current_generation, key=lambda x: x.grade, reverse=True) + + self.max_grade = self.current_generation[0].grade + self.min_grade = self.current_generation[len(self.current_generation) - 1].grade + self.avg_grade = sum([x.grade for x in self.current_generation])/self.population_size + for i in range(self.population_size): if i < self.population_size/2: self.current_generation[i].status = 'selected' else: self.current_generation[i].status = 'eliminated' self.state = 'select' if console: console('Generation %d of %s : evaluation complete'%(self.generation_count, self.name)) return def apply_selection(self, console = None): self.save_genomes() self.current_generation = self.current_generation[:self.population_size/2] self.state = 'reproduce' self.save() console('%s : applied selection on generation %d'%(self.name, self.generation_count)) return def reproduce(self, console = None): self.generation_count += 1 console('%s : reproducing of generation %d started'%(self.name, self.generation_count)) pool = [] index = 0 while self.current_generation: l = len(self.current_generation) - 1 if not l: break a = operators.r(l) parent_1 = self.current_generation[a] del self.current_generation[a] a = operators.r(l - 1) parent_2 = self.current_generation[a] del self.current_generation[a] child_1_g, child_2_g = operators.random_crossover(parent_1.note_list, parent_2.note_list) operators.random_mutator(child_1_g) operators.random_mutator(child_2_g) parent_1.individual_id = index parent_1.status = 'created' parent_1.generation = self.generation_count parent_1.grade = 0.0 index += 1 parent_2.individual_id = index parent_2.status = 'created' parent_2.generation = self.generation_count parent_2.grade = 0.0 index += 1 child_1 = song(child_1_g, self.name, self.generation_count, index, parent_1.name, parent_2.name) index += 1 child_2 = song(child_2_g, self.name, self.generation_count, index, parent_1.name, parent_2.name) index += 1 t = parent_1.note_list operators.random_mutator(t) parent_1.set_genome(t) t = parent_2.note_list operators.random_mutator(t) parent_2.set_genome(t) pool += [parent_1, parent_2, child_1, child_2] console('created %s and %s from %s and %s'%(child_1.name, child_2.name, parent_1.name, parent_2.name)) self.current_generation = pool self.save() self.save_genomes() self.state = 'evaluate' console('%s : created generation %d'%(self.name, self.generation_count)) diff --git a/src/main.py b/src/main.py index 02c4fc8..fc15f36 100755 --- a/src/main.py +++ b/src/main.py @@ -1,234 +1,244 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from mingus.midi import fluidsynth from util.storage import db from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), 'play' : self.builder.get_object('play_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') else: self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluate': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() + self.update_generation_info() return + def update_generation_info(self): + max_grade = str(self.evolution9.max_grade) + min_grade = str(self.evolution9.min_grade) + avg_grade = str(self.evolution9.avg_grade) + + self.builder.get_object('max_grade_label').set_text(max_grade) + self.builder.get_object('min_grade_label').set_text(min_grade) + self.builder.get_object('average_grade_label').set_text(avg_grade) + def reproduce(self, *args): self.evolution9.reproduce(self.log_console) self.update_state() self.update_genome_list() def on_initialize_button_clicked(self, *args): if self.evolution9.initialized: self.reproduce(*args) else: self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() def on_play_button_clicked(self, *args): index = self.genome_view.get_selection().get_selected()[1] index = self.genome_list.get_path(index)[0] fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index c900f86..6439dfc 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,896 +1,982 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label22"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Selected</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkLabel" id="selected_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_play_button_clicked"/> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> - <placeholder/> + <object class="GtkTable" id="table4"> + <property name="visible">True</property> + <property name="n_rows">3</property> + <property name="n_columns">2</property> + <child> + <object class="GtkLabel" id="label3"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Max. grade:</property> + </object> + <packing> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="max_grade_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label_min"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Min. grade</property> + </object> + <packing> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="min_grade_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label7"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Average grade:</property> + </object> + <packing> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="average_grade_label"> + <property name="visible">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> + <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="open_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Open evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox4"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkComboBox" id="evolution_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area4"> <property name="visible">True</property> <property name="layout_style">end</property> <child>
cagatay/Evolution-9
10f0cbfb411c03118376e2457f4a7d8f3daa5cfd
latest
diff --git a/src/brain/NN.py b/src/brain/NN.py index 38aead1..8a812b5 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,83 +1,85 @@ from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet from pybrain.tools.shortcuts import buildNetwork import constants import pickle import math from pybrain.auxiliary import GradientDescent from pybrain.structure import RecurrentNetwork, LinearLayer, SigmoidLayer, FullConnection import random from util import rttl import math class neural_network(object): def __init__(self, name, dataset, trained, store): self.name = name self.store = store self.trained = trained self.dataset = dataset ''' self.net = RecurrentNetwork() self.net.addInputModule(LinearLayer(2, name='in')) self.net.addModule(SigmoidLayer(3, name='hidden')) self.net.addOutputModule(LinearLayer(2, name='out')) self.net.addConnection(FullConnection(self.net['in'], self.net['out'], name='c1')) self.net.addConnection(FullConnection(self.net['hidden'], self.net['out'], name='c2')) self.net.addRecurrentConnection(FullConnection(self.net['hidden'], self.net['hidden'], name='c3')) self.net.sortModules() ''' self.net = buildNetwork(2, 3, 2) if not self.trained: self.train() return def save(self): self.store.save_neural_network(self.name, self.dataset, self.trained) return @classmethod def get_saved(cls, name, store): result = store.get_neural_network(name) return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) store.new_neural_network(name, dataset) return def evaluate(self, genome): err = 0.0 for i in range(len(genome) - 1): output = self.net.activate(genome[i]) target = genome[i + 1] - print output err += (math.fabs(output[0] - target[0]) + math.fabs(output[1] - target[1])) return 1/err def train(self): + ds_store = [] for song in self.dataset: ds_in = song[:len(song) - 1] ds_out = song[1:] ds = SupervisedDataSet(2, 2) for i in range(len(song) -1): - ds.addSample(ds_in[i], ds_out[i]) - - trainer = BackpropTrainer(self.net, ds, verbose=True) - trainer.trainEpochs(50) + if ds_in[i] not in ds_store: + ds.addSample(ds_in[i], ds_out[i]) + ds_store.append(ds_in[i]) + if len(ds): + trainer = BackpropTrainer(self.net, ds, verbose=True) + trainer.train() self.save()
cagatay/Evolution-9
1ec0dcbd4446f9332b38c41d89495d94136bb546
latest
diff --git a/src/brain/NN.py b/src/brain/NN.py index 3c54f90..38aead1 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,222 +1,83 @@ -from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer +from pybrain.datasets import SupervisedDataSet +from pybrain.tools.shortcuts import buildNetwork import constants import pickle import math from pybrain.auxiliary import GradientDescent from pybrain.structure import RecurrentNetwork, LinearLayer, SigmoidLayer, FullConnection import random from util import rttl +import math class neural_network(object): def __init__(self, name, dataset, trained, store): self.name = name self.store = store self.trained = trained self.dataset = dataset + ''' self.net = RecurrentNetwork() self.net.addInputModule(LinearLayer(2, name='in')) self.net.addModule(SigmoidLayer(3, name='hidden')) - self.net.addOutputModule(LinearLayer(1, name='out')) + self.net.addOutputModule(LinearLayer(2, name='out')) self.net.addConnection(FullConnection(self.net['in'], self.net['out'], name='c1')) self.net.addConnection(FullConnection(self.net['hidden'], self.net['out'], name='c2')) self.net.addRecurrentConnection(FullConnection(self.net['hidden'], self.net['hidden'], name='c3')) self.net.sortModules() + ''' + self.net = buildNetwork(2, 3, 2) - self.descent = GradientDescent() - self.descent.alpha = 0.01 - self.descent.momentum = 0.0 - self.descent.alphadecay = 1.0 - self.descent.init(self.net.params) - if not self.trained: self.train() return def save(self): self.store.save_neural_network(self.name, self.dataset, self.trained) return @classmethod def get_saved(cls, name, store): result = store.get_neural_network(name) return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) store.new_neural_network(name, dataset) return def evaluate(self, genome): - return random.random() + err = 0.0 + for i in range(len(genome) - 1): + output = self.net.activate(genome[i]) + target = genome[i + 1] + print output + err += (math.fabs(output[0] - target[0]) + math.fabs(output[1] - target[1])) - def train(self): - target = 1 - - descent = GradientDescent() - descent.alpha + return 1/err + def train(self): for song in self.dataset: - for note in song: - output = self.net.activate(note) + ds_in = song[:len(song) - 1] + ds_out = song[1:] - self.net.backActivate(output - target) + ds = SupervisedDataSet(2, 2) - for _ in range(len(song) - 1): - self.net.backActivate(0) + for i in range(len(song) -1): + ds.addSample(ds_in[i], ds_out[i]) - self.net._setParameters(self.descent(self.net.derivs)) - - print 'error: %d'%(output - target) + trainer = BackpropTrainer(self.net, ds, verbose=True) + trainer.trainEpochs(50) self.save() - - -''' -class NN: - name = "" - net = buildNetwork(1, 1, 1) - inputCount = 1 - outputCount = 1 - hiddenLayerNodeCount = 20 - durationPerNote = 2; - ds = SupervisedDataSet(inputCount, outputCount) - - - def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): - self.name= _name - self.inputCount = _inputCount - self.outputCount = _outputCount - self.durationPerNote = _durationPerNote - self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) - self.ds = SupervisedDataSet(self.inputCount, self.outputCount) - - def saveNetworkToFile(self): - pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" - + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) - - def readNetworkFromFile(self): - self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" - + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) - - def train(self): - trainer = BackpropTrainer(self.net, self.ds, verbose=True) - - trainer.trainUntilConvergence() -# for i in range(0,5000): -# trainer.trainEpochs(1) -# print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) -# trainer.trainEpochs(1) -# print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) -# - - - def addSong(self, song): - - song = self.attachIntList( song ) - - - - i = 0 - z = 0 - - for intNote in song.intList: - - if i + self.inputCount >= len( song.intList ): - break - - sampleList = list() - sampleOutputList = list() - - for j in range( 0, self.inputCount + 1 ): - - if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : - - - if( j + i + self.outputCount < len( song.intList ) ): - - for z in range( j + i , j + i + self.outputCount ): - #sampleOutputList.append( song.intList[ z ] ) - sampleOutputList.append( 1 ) - - self.ds.addSample( sampleList, sampleOutputList ) - - sampleList = list() - sampleOutputList = list() - - else: - sampleList.append( song.intList[ j + i ] ) - - i += 1 - - - - def attachIntList(self, song): - currentNoteInt = 0 - currentDuration = 0 - currentNote = Note() - song.intList = list() - for note in song.notes: - if not note[1]: - currentNote = None - currentNoteInt = 0 - currentDuration = note[0] - else: - currentNote = Note(note[1], note[2]) - currentNoteInt = int(Note(note[1], note[2])) - currentDuration = note[0] - - insertedDuration = 0 - while insertedDuration < currentDuration: - song.intList.append(currentNoteInt) - insertedDuration += 2 - return song - - - def fitness(self, song): - - returnValue = 0.0 - - song = self.attachIntList( song ) - - i = 0 - z = 0 - - for intNote in song.intList: - - if i + self.inputCount >= len( song.intList ): - break - - sampleList = list() - - for j in range( 0, self.inputCount + 1 ): - - if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : - - - if( j + i + self.outputCount < len( song.intList ) ): - - for z in range( j + i , j + i + self.outputCount ): - returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) - - sampleList = list() - - else: - sampleList.append( song.intList[ j + i ] ) - - i += 1 - - - return returnValue -''' diff --git a/src/main.py b/src/main.py index 2a7fd9f..02c4fc8 100755 --- a/src/main.py +++ b/src/main.py @@ -1,236 +1,234 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from mingus.midi import fluidsynth from util.storage import db from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), - 'graphs' : self.builder.get_object('generation_info_tab'), 'play' : self.builder.get_object('play_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') else: self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluate': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) - self.controls['graphs'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() return def reproduce(self, *args): self.evolution9.reproduce(self.log_console) self.update_state() self.update_genome_list() def on_initialize_button_clicked(self, *args): if self.evolution9.initialized: self.reproduce(*args) else: self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() def on_play_button_clicked(self, *args): index = self.genome_view.get_selection().get_selected()[1] index = self.genome_list.get_path(index)[0] fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index bf0478c..c900f86 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,941 +1,884 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label22"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Selected</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkLabel" id="selected_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_play_button_clicked"/> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> - <object class="GtkNotebook" id="generation_info_tab"> - <property name="visible">True</property> - <property name="sensitive">False</property> - <property name="can_focus">True</property> - <child> - <object class="GtkLabel" id="label6"> - <property name="visible">True</property> - <property name="label" translatable="yes">x grafigi</property> - </object> - </child> - <child type="tab"> - <object class="GtkLabel" id="label3"> - <property name="visible">True</property> - <property name="label" translatable="yes">page 1</property> - </object> - <packing> - <property name="tab_fill">False</property> - </packing> - </child> - <child> - <object class="GtkLabel" id="label7"> - <property name="visible">True</property> - <property name="label" translatable="yes">y grafigi</property> - </object> - <packing> - <property name="position">1</property> - </packing> - </child> - <child type="tab"> - <object class="GtkLabel" id="label4"> - <property name="visible">True</property> - <property name="label" translatable="yes">page 2</property> - </object> - <packing> - <property name="position">1</property> - <property name="tab_fill">False</property> - </packing> - </child> - <child> - <object class="GtkLabel" id="label8"> - <property name="visible">True</property> - <property name="label" translatable="yes">z grafigi</property> - </object> - <packing> - <property name="position">2</property> - </packing> - </child> - <child type="tab"> - <object class="GtkLabel" id="label5"> - <property name="visible">True</property> - <property name="label" translatable="yes">page 3</property> - </object> - <packing> - <property name="position">2</property> - <property name="tab_fill">False</property> - </packing> - </child> - </object> + <placeholder/> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="open_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Open evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox4"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkComboBox" id="evolution_combo"> <property name="visible">True</property> <property name="active">0</property> diff --git a/src/util/storage.py b/src/util/storage.py index ea5243f..794034d 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,198 +1,198 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 import json class db: _connection = None def __init__(self): self._connection = sqlite3.connect(SQLITE_FILE) c = self._cursor # Create neural networks table c.execute(''' CREATE TABLE IF NOT EXISTS neural_networks( name TEXT PRIMARY KEY ON CONFLICT REPLACE, dataset TEXT, trained BOOLEAN ); ''') # Create evolutions table c.execute(''' CREATE TABLE IF NOT EXISTS evolutions( name TEXT PRIMARY KEY ON CONFLICT REPLACE, population_size INTEGER, generation_count INTEGER, evaluator TEXT, state TEXT, FOREIGN KEY(evaluator) REFERENCES neural_networks(name) ); ''') # create genomes table c.execute(''' CREATE TABLE IF NOT EXISTS genomes( name TEXT PRIMARY KEY ON CONFLICT REPLACE, genome TEXT, evolution TEXT, generation INTEGER, individual_id, parent_1 TEXT, parent_2 TEXT, grade REAL, status TEXT, FOREIGN KEY(evolution) REFERENCES evolutions(name) ); ''') self._commit() c.close() def _commit(self): self._connection.commit() @property def _cursor(self): return self._connection.cursor() def close(self): self._connection.close() def save_evolution(self, name, population_size, evaluator, generation_count, state): c = self._cursor c.execute(''' INSERT INTO evolutions (name, evaluator, population_size, generation_count, state) VALUES(?, ?, ?, ?, ?); ''', (name, evaluator, population_size, generation_count, state)) self._commit() c.close() return #Returns evolution for the given row id def get_evolution(self, name): c = self._cursor c.execute(''' SELECT * FROM evolutions WHERE name=? ''', [name]) result = c.fetchall() c.close() return result[0] if result else None def get_evolution_list(self): c = self._cursor c.execute(''' SELECT name FROM evolutions ''') result = c.fetchall() c.close() return result def new_neural_network(self, name, dataset): c = self._cursor c.execute(''' INSERT INTO neural_networks (name, dataset, trained) VALUES(?, ?, ?); ''', (name, json.dumps(dataset), 0)) self._commit() c.close() return - def save_neural_network(self, dataset, trained): + def save_neural_network(self, name, dataset, trained): c = self._cursor c.execute(''' - UPDATE neural_networks SET trained=? WHERE name=?; - ''', (int(trained), json.dumps(dataset))) + UPDATE neural_networks SET name=?, trained=? WHERE name=?; + ''', (name, int(trained), json.dumps(dataset))) self._commit() c.close() return def get_neural_network(self, name): c = self._cursor c.execute(''' SELECT dataset, trained from neural_networks WHERE name=?; ''', [name]) result = c.fetchall()[0] c.close() return json.loads(result[0]), bool(result[1]) def get_neural_network_list(self): c = self._cursor c.execute(''' SELECT name FROM neural_networks ''') result = c.fetchall() c.close() return [x[0] for x in result] def get_genomes(self, evolution, generation): c = self._cursor c.execute(''' SELECT * FROM genomes WHERE evolution=? AND generation=? AND status <> ? ORDER BY individual_id ASC ''', [evolution, generation, 'eliminated']) result = c.fetchall() c.close() return result def save_genome(self, name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status): c = self._cursor c.execute(''' INSERT INTO genomes(name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?); ''', (name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status)) self._commit() c.close() return diff --git a/src/yedek.txt b/src/yedek.txt new file mode 100644 index 0000000..1e97d10 --- /dev/null +++ b/src/yedek.txt @@ -0,0 +1,138 @@ + +''' +class NN: + name = "" + net = buildNetwork(1, 1, 1) + inputCount = 1 + outputCount = 1 + hiddenLayerNodeCount = 20 + durationPerNote = 2; + ds = SupervisedDataSet(inputCount, outputCount) + + + def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): + self.name= _name + self.inputCount = _inputCount + self.outputCount = _outputCount + self.durationPerNote = _durationPerNote + self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) + self.ds = SupervisedDataSet(self.inputCount, self.outputCount) + + def saveNetworkToFile(self): + pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) + + def readNetworkFromFile(self): + self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) + + def train(self): +# trainer = BackpropTrainer(self.net, self.ds, verbose=True) + +# trainer.trainUntilConvergence() +# for i in range(0,5000): +# trainer.trainEpochs(1) +# print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) +# trainer.trainEpochs(1) +# print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) +# + + + def addSong(self, song): + + song = self.attachIntList( song ) + + + + i = 0 + z = 0 + + for intNote in song.intList: + + if i + self.inputCount >= len( song.intList ): + break + + sampleList = list() + sampleOutputList = list() + + for j in range( 0, self.inputCount + 1 ): + + if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : + + + if( j + i + self.outputCount < len( song.intList ) ): + + for z in range( j + i , j + i + self.outputCount ): + #sampleOutputList.append( song.intList[ z ] ) + sampleOutputList.append( 1 ) + + self.ds.addSample( sampleList, sampleOutputList ) + + sampleList = list() + sampleOutputList = list() + + else: + sampleList.append( song.intList[ j + i ] ) + + i += 1 + + + + def attachIntList(self, song): + currentNoteInt = 0 + currentDuration = 0 + currentNote = Note() + song.intList = list() + for note in song.notes: + if not note[1]: + currentNote = None + currentNoteInt = 0 + currentDuration = note[0] + else: + currentNote = Note(note[1], note[2]) + currentNoteInt = int(Note(note[1], note[2])) + currentDuration = note[0] + + insertedDuration = 0 + while insertedDuration < currentDuration: + song.intList.append(currentNoteInt) + insertedDuration += 2 + return song + + + def fitness(self, song): + + returnValue = 0.0 + + song = self.attachIntList( song ) + + i = 0 + z = 0 + + for intNote in song.intList: + + if i + self.inputCount >= len( song.intList ): + break + + sampleList = list() + + for j in range( 0, self.inputCount + 1 ): + + if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : + + + if( j + i + self.outputCount < len( song.intList ) ): + + for z in range( j + i , j + i + self.outputCount ): + returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) + + sampleList = list() + + else: + sampleList.append( song.intList[ j + i ] ) + + i += 1 + + + return returnValue +'''
cagatay/Evolution-9
ea325f47017b574a1a3cd4c0b120f2f33d859551
neural network
diff --git a/src/brain/NN.py b/src/brain/NN.py index c175334..3c54f90 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,185 +1,222 @@ -from pybrain.tools.shortcuts import buildNetwork from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer -from pybrain.datasets import SupervisedDataSet import constants import pickle import math +from pybrain.auxiliary import GradientDescent +from pybrain.structure import RecurrentNetwork, LinearLayer, SigmoidLayer, FullConnection import random from util import rttl class neural_network(object): def __init__(self, name, dataset, trained, store): self.name = name self.store = store - self.trained = True + self.trained = trained self.dataset = dataset + self.net = RecurrentNetwork() + self.net.addInputModule(LinearLayer(2, name='in')) + self.net.addModule(SigmoidLayer(3, name='hidden')) + self.net.addOutputModule(LinearLayer(1, name='out')) + self.net.addConnection(FullConnection(self.net['in'], self.net['out'], name='c1')) + self.net.addConnection(FullConnection(self.net['hidden'], self.net['out'], name='c2')) + self.net.addRecurrentConnection(FullConnection(self.net['hidden'], self.net['hidden'], name='c3')) + self.net.sortModules() + + self.descent = GradientDescent() + self.descent.alpha = 0.01 + self.descent.momentum = 0.0 + self.descent.alphadecay = 1.0 + self.descent.init(self.net.params) + + if not self.trained: + self.train() + return def save(self): self.store.save_neural_network(self.name, self.dataset, self.trained) return @classmethod def get_saved(cls, name, store): result = store.get_neural_network(name) return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) store.new_neural_network(name, dataset) return def evaluate(self, genome): return random.random() def train(self): + target = 1 + + descent = GradientDescent() + descent.alpha + + for song in self.dataset: + for note in song: + output = self.net.activate(note) + + self.net.backActivate(output - target) + + for _ in range(len(song) - 1): + self.net.backActivate(0) + + self.net._setParameters(self.descent(self.net.derivs)) + + print 'error: %d'%(output - target) + self.save() + ''' class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 hiddenLayerNodeCount = 20 durationPerNote = 2; ds = SupervisedDataSet(inputCount, outputCount) def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount self.durationPerNote = _durationPerNote self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) def train(self): trainer = BackpropTrainer(self.net, self.ds, verbose=True) trainer.trainUntilConvergence() # for i in range(0,5000): # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) # def addSong(self, song): song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): #sampleOutputList.append( song.intList[ z ] ) sampleOutputList.append( 1 ) self.ds.addSample( sampleList, sampleOutputList ) sampleList = list() sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 return song def fitness(self, song): returnValue = 0.0 song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 return returnValue '''
cagatay/Evolution-9
e321f67621d610e20faccdad311a5b5b7a418566
improvements
diff --git a/src/evolution/genome.py b/src/evolution/genome.py index e7fa3fd..ab6a459 100644 --- a/src/evolution/genome.py +++ b/src/evolution/genome.py @@ -1,43 +1,48 @@ from util import rttl from mingus.containers.Track import Track class song(object): def __init__(self, genome, evolution, generation, individual_id, parent_1 = '', parent_2 = '', grade = 0.0, status = 'created'): - if type(genome) is list: - self.note_list = genome - self.genome = rttl.dump(genome) - - elif type(genome) is unicode: - self.genome = genome - self.note_list = rttl.parse(genome) - - self.int_list = rttl.to_int(self.note_list) - + self.evolution = evolution self.generation = generation self.parent_1 = parent_1 self.parent_2 = parent_2 self.grade = grade self.status = status self.individual_id = individual_id + self.set_genome(genome) + self.mingus_track = Track() for n in self.note_list: self.mingus_track.add_notes(n.mingus_note, n.mingus_duration) self.name = self.evolution + '-' + str(self.generation) + '-' + str(self.individual_id) return @property def selected(self): return self.status == 'selected' + + def set_genome(self, genome): + if type(genome) is list: + self.note_list = genome + self.genome = rttl.dump(genome) + + elif type(genome) is unicode: + self.genome = genome + self.note_list = rttl.parse(genome) + + self.int_list = rttl.to_int(self.note_list) + diff --git a/src/evolution/manager.py b/src/evolution/manager.py index 267c55c..bd546fc 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,116 +1,191 @@ from brain.NN import neural_network from evolution import operators from evolution.genome import song class evolution(object): def __init__(self, name, evaluator, population_size, store, generation_count = 0, state='uninitialized'): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = generation_count self.state = state if self.state != 'uninitialized': self.get_current_generation() else: self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, self.state) return def save_genomes(self): for g in self.current_generation: self.store.save_genome(g.name, g.genome, g.evolution, g.generation, g.individual_id, g.parent_1, g.parent_2, g.grade, g.status) return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) return cls(result[0], result[3], result[1], store, result[2], result[4]) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None def initialize(self, console = None): self.current_generation = [] for i in xrange(self.population_size): g = song(operators.random_genome(), self.name, 0, i) self.current_generation.append(g) - self.state = 'evaluation' + self.state = 'evaluate' self.save_genomes() self.save() if console: console('%s is initialized'%self.name) return @property def initialized(self): return self.state != 'uninitialized' def get_current_generation(self): result = self.store.get_genomes(self.name, self.generation_count) if result: self.current_generation = [] for i in result: g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) self.current_generation.append(g) return def evaluate(self, console = None): self.results = [] for g in self.current_generation: result = self.evaluator.evaluate(g.int_list) g.grade = result if console: console('%s evaluation result: %f'%(g.name, result)) self.current_generation = sorted(self.current_generation, key=lambda x: x.grade, reverse=True) for i in range(self.population_size): if i < self.population_size/2: self.current_generation[i].status = 'selected' else: self.current_generation[i].status = 'eliminated' self.state = 'select' if console: console('Generation %d of %s : evaluation complete'%(self.generation_count, self.name)) return def apply_selection(self, console = None): self.save_genomes() self.current_generation = self.current_generation[:self.population_size/2] self.state = 'reproduce' self.save() console('%s : applied selection on generation %d'%(self.name, self.generation_count)) return def reproduce(self, console = None): + self.generation_count += 1 + + console('%s : reproducing of generation %d started'%(self.name, self.generation_count)) + + pool = [] + + index = 0 + while self.current_generation: + l = len(self.current_generation) - 1 + + if not l: + break + + a = operators.r(l) + + parent_1 = self.current_generation[a] + del self.current_generation[a] + + a = operators.r(l - 1) + parent_2 = self.current_generation[a] + + del self.current_generation[a] + + child_1_g, child_2_g = operators.random_crossover(parent_1.note_list, + parent_2.note_list) + operators.random_mutator(child_1_g) + operators.random_mutator(child_2_g) + + parent_1.individual_id = index + parent_1.status = 'created' + parent_1.generation = self.generation_count + parent_1.grade = 0.0 + index += 1 + + parent_2.individual_id = index + parent_2.status = 'created' + parent_2.generation = self.generation_count + parent_2.grade = 0.0 + index += 1 + + child_1 = song(child_1_g, + self.name, + self.generation_count, + index, + parent_1.name, + parent_2.name) + index += 1 + + child_2 = song(child_2_g, + self.name, + self.generation_count, + index, + parent_1.name, + parent_2.name) + index += 1 + + t = parent_1.note_list + operators.random_mutator(t) + parent_1.set_genome(t) + + t = parent_2.note_list + operators.random_mutator(t) + parent_2.set_genome(t) + + pool += [parent_1, parent_2, child_1, child_2] + + console('created %s and %s from %s and %s'%(child_1.name, child_2.name, parent_1.name, parent_2.name)) + + self.current_generation = pool + + self.save() + self.save_genomes() + self.state = 'evaluate' + console('%s : created generation %d'%(self.name, self.generation_count)) + diff --git a/src/main.py b/src/main.py index 20faa28..2a7fd9f 100755 --- a/src/main.py +++ b/src/main.py @@ -1,228 +1,236 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from mingus.midi import fluidsynth from util.storage import db from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), 'graphs' : self.builder.get_object('generation_info_tab'), 'play' : self.builder.get_object('play_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') else: self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) - elif self.evolution9.state == 'evaluation': + elif self.evolution9.state == 'evaluate': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.controls['graphs'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() return - def on_initialize_button_clicked(self, *args): - self.evolution9.initialize(self.log_console) - self.controls['initialize'].set_label('Reproduce') + def reproduce(self, *args): + self.evolution9.reproduce(self.log_console) self.update_state() self.update_genome_list() + def on_initialize_button_clicked(self, *args): + if self.evolution9.initialized: + self.reproduce(*args) + else: + self.evolution9.initialize(self.log_console) + self.controls['initialize'].set_label('Reproduce') + self.update_state() + self.update_genome_list() + def on_play_button_clicked(self, *args): index = self.genome_view.get_selection().get_selected()[1] index = self.genome_list.get_path(index)[0] fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main()
cagatay/Evolution-9
d929ca1534bb66eca055fbdb8105444485e48c68
improvements, gui work
diff --git a/src/constants.py b/src/constants.py index 71081ea..101957c 100644 --- a/src/constants.py +++ b/src/constants.py @@ -1,10 +1,11 @@ ''' Created on Oct 10, 2010 @author: cagatay.yuksel ''' SQLITE_FILE = "../data/evolution9.db" OUTPUT_DIR = "../output/" INPUT_DIR = "../inputs/" -SAVE_DIR = "../save/" \ No newline at end of file +SAVE_DIR = "../save/" +MIDI_FILE = '../midi/Ultimate.SF2' diff --git a/src/evolution/genome.py b/src/evolution/genome.py index f678375..e7fa3fd 100644 --- a/src/evolution/genome.py +++ b/src/evolution/genome.py @@ -1,37 +1,43 @@ from util import rttl +from mingus.containers.Track import Track class song(object): def __init__(self, genome, evolution, generation, individual_id, parent_1 = '', parent_2 = '', grade = 0.0, status = 'created'): if type(genome) is list: self.note_list = genome self.genome = rttl.dump(genome) elif type(genome) is unicode: self.genome = genome self.note_list = rttl.parse(genome) self.int_list = rttl.to_int(self.note_list) self.evolution = evolution self.generation = generation self.parent_1 = parent_1 self.parent_2 = parent_2 self.grade = grade self.status = status self.individual_id = individual_id + self.mingus_track = Track() + + for n in self.note_list: + self.mingus_track.add_notes(n.mingus_note, n.mingus_duration) + self.name = self.evolution + '-' + str(self.generation) + '-' + str(self.individual_id) return @property def selected(self): return self.status == 'selected' diff --git a/src/evolution/manager.py b/src/evolution/manager.py index 9650481..267c55c 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,114 +1,116 @@ from brain.NN import neural_network from evolution import operators from evolution.genome import song class evolution(object): def __init__(self, name, evaluator, population_size, store, generation_count = 0, state='uninitialized'): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = generation_count self.state = state if self.state != 'uninitialized': self.get_current_generation() else: self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, self.state) return def save_genomes(self): for g in self.current_generation: self.store.save_genome(g.name, g.genome, g.evolution, g.generation, g.individual_id, g.parent_1, g.parent_2, g.grade, g.status) return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) return cls(result[0], result[3], result[1], store, result[2], result[4]) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None def initialize(self, console = None): self.current_generation = [] for i in xrange(self.population_size): g = song(operators.random_genome(), self.name, 0, i) self.current_generation.append(g) self.state = 'evaluation' self.save_genomes() self.save() if console: console('%s is initialized'%self.name) return @property def initialized(self): return self.state != 'uninitialized' def get_current_generation(self): result = self.store.get_genomes(self.name, self.generation_count) if result: self.current_generation = [] for i in result: g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) self.current_generation.append(g) return def evaluate(self, console = None): self.results = [] for g in self.current_generation: result = self.evaluator.evaluate(g.int_list) g.grade = result if console: console('%s evaluation result: %f'%(g.name, result)) self.current_generation = sorted(self.current_generation, key=lambda x: x.grade, reverse=True) for i in range(self.population_size): if i < self.population_size/2: self.current_generation[i].status = 'selected' else: self.current_generation[i].status = 'eliminated' self.state = 'select' if console: console('Generation %d of %s : evaluation complete'%(self.generation_count, self.name)) return def apply_selection(self, console = None): self.save_genomes() self.current_generation = self.current_generation[:self.population_size/2] self.state = 'reproduce' self.save() console('%s : applied selection on generation %d'%(self.name, self.generation_count)) return + + def reproduce(self, console = None): diff --git a/src/main.py b/src/main.py index 878ef3a..20faa28 100755 --- a/src/main.py +++ b/src/main.py @@ -1,218 +1,228 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution +from mingus.midi import fluidsynth from util.storage import db +from constants import MIDI_FILE class evolution9_app(object): def __init__(self): self.store = db() + fluidsynth.init(MIDI_FILE, 'alsa') self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), 'graphs' : self.builder.get_object('generation_info_tab'), 'play' : self.builder.get_object('play_button') } self.console = gtk.TextBuffer() self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def log_console(self, text): self.console.insert_at_cursor(text + '\n') self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') + else: + self.controls['initialize'].set_label('Initialize') self.update_state() self.update_genome_list() self.log_console('%s is started'%self.evolution9.name) #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluation': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.controls['graphs'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_apply_selection_button_clicked(self, *args): self.evolution9.apply_selection(self.log_console) self.update_genome_list() self.update_state() def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_evaluate_button_clicked(self, *args): self.evolution9.evaluate(self.log_console) self.update_genome_list() self.update_state() return def on_initialize_button_clicked(self, *args): self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() + + def on_play_button_clicked(self, *args): + index = self.genome_view.get_selection().get_selected()[1] + index = self.genome_list.get_path(index)[0] + fluidsynth.play_Track(self.evolution9.current_generation[index].mingus_track) if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 0e7307a..bf0478c 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,890 +1,891 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label22"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Selected</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkLabel" id="selected_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> + <signal name="clicked" handler="on_play_button_clicked"/> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkNotebook" id="generation_info_tab"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <child> <object class="GtkLabel" id="label6"> <property name="visible">True</property> - <property name="label" translatable="yes">x graifigi</property> + <property name="label" translatable="yes">x grafigi</property> </object> </child> <child type="tab"> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </object> <packing> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="label" translatable="yes">y grafigi</property> </object> <packing> <property name="position">1</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </object> <packing> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="label" translatable="yes">z grafigi</property> </object> <packing> <property name="position">2</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </object> <packing> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> diff --git a/src/util/music.py b/src/util/music.py index e44802e..581bd42 100644 --- a/src/util/music.py +++ b/src/util/music.py @@ -1,34 +1,34 @@ import random from mingus.containers.Note import Note from mingus.core import value note_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] dot_range = ['.', ''] class note(object): def __init__(self, note, octave, duration, dot): self.note = str(note) self.octave = '' if octave is None else octave self.duration = duration self.dot = dot + self.mingus_duration = value.dots(int(self.duration), int(bool(self.dot))) if self.note == 'P': - self.mingus_note = '0' + self.mingus_note = None else: self.mingus_note = Note(self.note, int(self.octave)) def int_tuple(self): - return (int(self.mingus_note), - value.dots(int(self.duration), int(bool(self.dot)))) + return (int(self.mingus_note) if self.mingus_note else 0, self.mingus_duration) def __str__(self): return self.duration + self.note + self.dot + self.octave def random_note(): return note(random.choice(note_range), random.choice(octave_range), random.choice(duration_range), random.choice(dot_range))
cagatay/Evolution-9
7916746244d2de079e6b6bc1516363d5ee905e00
improvements, gui work
diff --git a/src/evolution/genome.py b/src/evolution/genome.py index 421be09..f678375 100644 --- a/src/evolution/genome.py +++ b/src/evolution/genome.py @@ -1,32 +1,37 @@ from util import rttl class song(object): def __init__(self, genome, evolution, generation, individual_id, parent_1 = '', parent_2 = '', grade = 0.0, status = 'created'): if type(genome) is list: self.note_list = genome self.genome = rttl.dump(genome) elif type(genome) is unicode: self.genome = genome self.note_list = rttl.parse(genome) self.int_list = rttl.to_int(self.note_list) self.evolution = evolution self.generation = generation self.parent_1 = parent_1 self.parent_2 = parent_2 self.grade = grade self.status = status self.individual_id = individual_id self.name = self.evolution + '-' + str(self.generation) + '-' + str(self.individual_id) + return + + @property + def selected(self): + return self.status == 'selected' diff --git a/src/evolution/manager.py b/src/evolution/manager.py index 79cda48..9650481 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,80 +1,114 @@ from brain.NN import neural_network from evolution import operators from evolution.genome import song class evolution(object): def __init__(self, name, evaluator, population_size, store, generation_count = 0, state='uninitialized'): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = generation_count self.state = state if self.state != 'uninitialized': self.get_current_generation() else: self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, self.state) return def save_genomes(self): for g in self.current_generation: self.store.save_genome(g.name, g.genome, g.evolution, g.generation, g.individual_id, g.parent_1, g.parent_2, g.grade, g.status) return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) return cls(result[0], result[3], result[1], store, result[2], result[4]) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None - def initialize(self): + def initialize(self, console = None): self.current_generation = [] for i in xrange(self.population_size): g = song(operators.random_genome(), self.name, 0, i) self.current_generation.append(g) self.state = 'evaluation' self.save_genomes() self.save() + + if console: + console('%s is initialized'%self.name) return @property def initialized(self): return self.state != 'uninitialized' def get_current_generation(self): result = self.store.get_genomes(self.name, self.generation_count) if result: self.current_generation = [] for i in result: g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) self.current_generation.append(g) return + def evaluate(self, console = None): + self.results = [] + for g in self.current_generation: + result = self.evaluator.evaluate(g.int_list) + g.grade = result + if console: + console('%s evaluation result: %f'%(g.name, result)) + + self.current_generation = sorted(self.current_generation, key=lambda x: x.grade, reverse=True) + for i in range(self.population_size): + if i < self.population_size/2: + self.current_generation[i].status = 'selected' + else: + self.current_generation[i].status = 'eliminated' + self.state = 'select' + + if console: + console('Generation %d of %s : evaluation complete'%(self.generation_count, self.name)) + return + + def apply_selection(self, console = None): + self.save_genomes() + + self.current_generation = self.current_generation[:self.population_size/2] + self.state = 'reproduce' + + self.save() + + console('%s : applied selection on generation %d'%(self.name, self.generation_count)) + + return diff --git a/src/main.py b/src/main.py index ff2d829..878ef3a 100755 --- a/src/main.py +++ b/src/main.py @@ -1,195 +1,218 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from util.storage import db class evolution9_app(object): def __init__(self): self.store = db() self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) self.controls = { 'initialize': self.builder.get_object('initialize_button'), 'evaluate': self.builder.get_object('evaluate_button'), 'select' : self.builder.get_object('apply_selection_button'), 'graphs' : self.builder.get_object('generation_info_tab'), 'play' : self.builder.get_object('play_button') } + + self.console = gtk.TextBuffer() + self.builder.get_object('console').set_buffer(self.console) # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) + def log_console(self, text): + self.console.insert_at_cursor(text + '\n') + self.builder.get_object('console').scroll_to_mark(self.console.get_insert(), 0) + + def start_evolution(self): if self.evolution9.initialized: self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() + self.log_console('%s is started'%self.evolution9.name) + #self.builder.get_object('generation_info_tab').set_sensitive(True) def update_state(self): for k, v in self.controls.iteritems(): v.set_sensitive(False) if self.evolution9: - if not self.evolution9.initialized or self.evolution9.state == 'reproduction': + if not self.evolution9.initialized or self.evolution9.state == 'reproduce': self.controls['initialize'].set_sensitive(True) elif self.evolution9.state == 'evaluation': self.controls['evaluate'].set_sensitive(True) elif self.evolution9.state == 'select': self.controls['select'].set_sensitive(True) self.controls['graphs'].set_sensitive(True) self.builder.get_object('step_50_button').set_sensitive(True) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def show_individual_info(self, treeview, path, view_column, *args): index = path[0] individual = self.evolution9.current_generation[index] self.builder.get_object('name_label').set_text(individual.name) self.builder.get_object('parent1_label').set_text(individual.parent_1) self.builder.get_object('parent2_label').set_text(individual.parent_2) self.builder.get_object('grade_label').set_text(str(individual.grade)) + self.builder.get_object('selected_label').set_text(str(individual.selected)) self.controls['play'].set_sensitive(True) def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return + def on_apply_selection_button_clicked(self, *args): + self.evolution9.apply_selection(self.log_console) + self.update_genome_list() + self.update_state() + def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: + self.log_console('created neural network : %s' % nn_name) self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() + def on_evaluate_button_clicked(self, *args): + self.evolution9.evaluate(self.log_console) + self.update_genome_list() + self.update_state() + return + def on_initialize_button_clicked(self, *args): - self.evolution9.initialize() + self.evolution9.initialize(self.log_console) self.controls['initialize'].set_label('Reproduce') self.update_state() self.update_genome_list() if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index f82709d..0e7307a 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,950 +1,979 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">900</property> <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="evaluate_button"> <property name="label" translatable="yes">Evaluate generation</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> + <signal name="clicked" handler="on_evaluate_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="apply_selection_button"> <property name="label" translatable="yes">Apply Selection</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> + <signal name="clicked" handler="on_apply_selection_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">50&gt;&gt;</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> - <property name="n_rows">4</property> + <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label18"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Name:</property> </object> <packing> <property name="x_options">GTK_FILL</property> <property name="y_options">GTK_FILL</property> </packing> </child> <child> <object class="GtkLabel" id="name_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label19"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 1:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="parent1_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label20"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Parent 2:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="parent2_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label21"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Grade:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="grade_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> + <child> + <object class="GtkLabel" id="label22"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Selected</property> + </object> + <packing> + <property name="top_attach">4</property> + <property name="bottom_attach">5</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="selected_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">4</property> + <property name="bottom_attach">5</property> + </packing> + </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="play_button"> <property name="label" translatable="yes">Play</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkNotebook" id="generation_info_tab"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <child> <object class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="label" translatable="yes">x graifigi</property> </object> </child> <child type="tab"> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </object> <packing> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="label" translatable="yes">y grafigi</property> </object> <packing> <property name="position">1</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </object> <packing> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="label" translatable="yes">z grafigi</property> </object> <packing> <property name="position">2</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </object> <packing> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> - <object class="GtkTextView" id="textview1"> + <object class="GtkTextView" id="console"> <property name="visible">True</property> <property name="can_focus">True</property> + <property name="editable">False</property> + <property name="wrap_mode">char</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="open_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Open evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox4"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkComboBox" id="evolution_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area4"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="open_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">open_evolution_ok_button</action-widget> </action-widgets> </object> </interface> diff --git a/src/util/storage.py b/src/util/storage.py index 3a57805..ea5243f 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,198 +1,198 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 import json class db: _connection = None def __init__(self): self._connection = sqlite3.connect(SQLITE_FILE) c = self._cursor # Create neural networks table c.execute(''' CREATE TABLE IF NOT EXISTS neural_networks( name TEXT PRIMARY KEY ON CONFLICT REPLACE, dataset TEXT, trained BOOLEAN ); ''') # Create evolutions table c.execute(''' CREATE TABLE IF NOT EXISTS evolutions( name TEXT PRIMARY KEY ON CONFLICT REPLACE, population_size INTEGER, generation_count INTEGER, evaluator TEXT, state TEXT, FOREIGN KEY(evaluator) REFERENCES neural_networks(name) ); ''') # create genomes table c.execute(''' CREATE TABLE IF NOT EXISTS genomes( name TEXT PRIMARY KEY ON CONFLICT REPLACE, genome TEXT, evolution TEXT, generation INTEGER, individual_id, parent_1 TEXT, parent_2 TEXT, grade REAL, status TEXT, FOREIGN KEY(evolution) REFERENCES evolutions(name) ); ''') self._commit() c.close() def _commit(self): self._connection.commit() @property def _cursor(self): return self._connection.cursor() def close(self): self._connection.close() def save_evolution(self, name, population_size, evaluator, generation_count, state): c = self._cursor c.execute(''' INSERT INTO evolutions (name, evaluator, population_size, generation_count, state) VALUES(?, ?, ?, ?, ?); ''', (name, evaluator, population_size, generation_count, state)) self._commit() c.close() return #Returns evolution for the given row id def get_evolution(self, name): c = self._cursor c.execute(''' SELECT * FROM evolutions WHERE name=? ''', [name]) result = c.fetchall() c.close() return result[0] if result else None def get_evolution_list(self): c = self._cursor c.execute(''' SELECT name FROM evolutions ''') result = c.fetchall() c.close() return result def new_neural_network(self, name, dataset): c = self._cursor c.execute(''' INSERT INTO neural_networks (name, dataset, trained) VALUES(?, ?, ?); ''', (name, json.dumps(dataset), 0)) self._commit() c.close() return def save_neural_network(self, dataset, trained): c = self._cursor c.execute(''' UPDATE neural_networks SET trained=? WHERE name=?; ''', (int(trained), json.dumps(dataset))) self._commit() c.close() return def get_neural_network(self, name): c = self._cursor c.execute(''' SELECT dataset, trained from neural_networks WHERE name=?; ''', [name]) result = c.fetchall()[0] c.close() return json.loads(result[0]), bool(result[1]) def get_neural_network_list(self): c = self._cursor c.execute(''' SELECT name FROM neural_networks ''') result = c.fetchall() c.close() return [x[0] for x in result] def get_genomes(self, evolution, generation): c = self._cursor c.execute(''' - SELECT * FROM genomes WHERE evolution=? AND generation=? ORDER BY individual_id ASC - ''', [evolution, generation]) + SELECT * FROM genomes WHERE evolution=? AND generation=? AND status <> ? ORDER BY individual_id ASC + ''', [evolution, generation, 'eliminated']) result = c.fetchall() c.close() return result def save_genome(self, name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status): c = self._cursor c.execute(''' INSERT INTO genomes(name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?); ''', (name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status)) self._commit() c.close() return
cagatay/Evolution-9
330e6f1dba6bee2a6ae8a60e389be73879695ad5
gui work
diff --git a/src/evolution/manager.py b/src/evolution/manager.py index 888b6c5..79cda48 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,76 +1,80 @@ from brain.NN import neural_network from evolution import operators from evolution.genome import song class evolution(object): - def __init__(self, name, evaluator, population_size, store, generation_count = 0, initialized = False): + def __init__(self, name, evaluator, population_size, store, generation_count = 0, state='uninitialized'): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = generation_count - self.initialized = initialized - if initialized: + self.state = state + if self.state != 'uninitialized': self.get_current_generation() else: self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, - self.initialized) + self.state) return def save_genomes(self): for g in self.current_generation: self.store.save_genome(g.name, g.genome, g.evolution, g.generation, g.individual_id, g.parent_1, g.parent_2, g.grade, g.status) return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) - return cls(result[0], result[3], result[1], store, result[2], bool(result[4])) if result else None + return cls(result[0], result[3], result[1], store, result[2], result[4]) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None def initialize(self): self.current_generation = [] for i in xrange(self.population_size): g = song(operators.random_genome(), self.name, 0, i) self.current_generation.append(g) - self.initialized = True + self.state = 'evaluation' self.save_genomes() self.save() return + @property + def initialized(self): + return self.state != 'uninitialized' + def get_current_generation(self): result = self.store.get_genomes(self.name, self.generation_count) if result: self.current_generation = [] for i in result: g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) self.current_generation.append(g) return diff --git a/src/main.py b/src/main.py index a7c76f8..ff2d829 100755 --- a/src/main.py +++ b/src/main.py @@ -1,162 +1,195 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from util.storage import db class evolution9_app(object): def __init__(self): self.store = db() self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() self.evolution_list = gtk.ListStore(str) self.evolution_combo = self.builder.get_object('evolution_combo') self.evolution_combo.set_model(self.evolution_list) cell = gtk.CellRendererText() self.evolution_combo.pack_start(cell, True) self.evolution_combo.add_attribute(cell, 'text', 0) self.update_evolution_list() self.genome_list = gtk.ListStore(int, str) self.genome_view = self.builder.get_object('genome_view') self.genome_view.set_model(self.genome_list) cell = gtk.CellRendererText() column = gtk.TreeViewColumn('Genome', cell, text=1) self.genome_view.append_column(column) + + self.controls = { + 'initialize': self.builder.get_object('initialize_button'), + 'evaluate': self.builder.get_object('evaluate_button'), + 'select' : self.builder.get_object('apply_selection_button'), + 'graphs' : self.builder.get_object('generation_info_tab'), + 'play' : self.builder.get_object('play_button') + } # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def start_evolution(self): - if not self.evolution9.initialized: - self.builder.get_object('initialize_button').set_sensitive(True) - self.builder.get_object('step_1_button').set_sensitive(True) - self.builder.get_object('step_50_button').set_sensitive(True) - self.builder.get_object('generation_info_tab').set_sensitive(True) - + if self.evolution9.initialized: + self.controls['initialize'].set_label('Reproduce') + self.update_state() self.update_genome_list() + #self.builder.get_object('generation_info_tab').set_sensitive(True) + def update_state(self): + for k, v in self.controls.iteritems(): + v.set_sensitive(False) + + if self.evolution9: + if not self.evolution9.initialized or self.evolution9.state == 'reproduction': + self.controls['initialize'].set_sensitive(True) + elif self.evolution9.state == 'evaluation': + self.controls['evaluate'].set_sensitive(True) + elif self.evolution9.state == 'select': + self.controls['select'].set_sensitive(True) + self.controls['graphs'].set_sensitive(True) + + self.builder.get_object('step_50_button').set_sensitive(True) + def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() + def show_individual_info(self, treeview, path, view_column, *args): + index = path[0] + individual = self.evolution9.current_generation[index] + + self.builder.get_object('name_label').set_text(individual.name) + self.builder.get_object('parent1_label').set_text(individual.parent_1) + self.builder.get_object('parent2_label').set_text(individual.parent_2) + self.builder.get_object('grade_label').set_text(str(individual.grade)) + + self.controls['play'].set_sensitive(True) + def main(self): self.window.show() gtk.main() def update_evolution_list(self): self.evolution_list.clear() evolutions = evolution.get_list(self.store) if evolutions: for e in evolutions: self.evolution_combo.append_text(e) return def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) return def update_genome_list(self): self.genome_list.clear() l = self.evolution9.current_generation if l: for x in range(len(l)): self.genome_list.append((x, l[x].genome)) return def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() self.start_evolution() def on_open_evolution_button_clicked(self, *args): self.open_evolution_dialog.present() return def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() return def on_open_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('evolution_combo').get_active_text() try: self.evolution9 = evolution.get_saved(name, self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.start_evolution() self.open_evolution_dialog.hide() def on_initialize_button_clicked(self, *args): self.evolution9.initialize() - self.builder.get_object('initialize_button').set_sensitive(False) + self.controls['initialize'].set_label('Reproduce') + self.update_state() self.update_genome_list() if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 000d916..f82709d 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,729 +1,828 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> - <property name="default_width">800</property> - <property name="default_height">600</property> + <property name="default_width">900</property> + <property name="default_height">700</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> - <object class="GtkHButtonBox" id="hbuttonbox1"> + <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> - <property name="layout_style">end</property> <child> - <object class="GtkButton" id="initialize_button"> - <property name="label" translatable="yes">Initialize</property> + <object class="GtkHButtonBox" id="hbuttonbox3"> <property name="visible">True</property> - <property name="sensitive">False</property> - <property name="can_focus">True</property> - <property name="receives_default">True</property> - <signal name="clicked" handler="on_initialize_button_clicked"/> + <property name="layout_style">start</property> + <child> + <object class="GtkButton" id="initialize_button"> + <property name="label" translatable="yes">Initialize</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_initialize_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="evaluate_button"> + <property name="label" translatable="yes">Evaluate generation</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="apply_selection_button"> + <property name="label" translatable="yes">Apply Selection</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">2</property> + </packing> + </child> </object> <packing> <property name="expand">False</property> - <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> - <object class="GtkButton" id="step_1_button"> - <property name="label" translatable="yes">Step 1</property> + <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> - <property name="sensitive">False</property> - <property name="can_focus">True</property> - <property name="receives_default">True</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="step_50_button"> + <property name="label" translatable="yes">50&gt;&gt;</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> </object> <packing> <property name="expand">False</property> - <property name="fill">False</property> + <property name="pack_type">end</property> <property name="position">1</property> </packing> </child> - <child> - <object class="GtkButton" id="step_50_button"> - <property name="label" translatable="yes">Step 50</property> - <property name="visible">True</property> - <property name="sensitive">False</property> - <property name="can_focus">True</property> - <property name="receives_default">True</property> - </object> - <packing> - <property name="expand">False</property> - <property name="fill">False</property> - <property name="position">2</property> - </packing> - </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="enable_search">False</property> - <property name="ubuntu_almost_fixed_height_mode">True</property> + <signal name="row_activated" handler="show_individual_info"/> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> - <object class="GtkTable" id="table1"> + <object class="GtkVBox" id="vbox7"> <property name="visible">True</property> - <property name="n_rows">9</property> - <property name="n_columns">2</property> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> + <property name="orientation">vertical</property> <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> - </child> - <child> - <placeholder/> + <object class="GtkTable" id="table1"> + <property name="visible">True</property> + <property name="n_rows">4</property> + <property name="n_columns">2</property> + <child> + <object class="GtkLabel" id="label18"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Name:</property> + </object> + <packing> + <property name="x_options">GTK_FILL</property> + <property name="y_options">GTK_FILL</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="name_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label19"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Parent 1:</property> + </object> + <packing> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="parent1_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label20"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Parent 2:</property> + </object> + <packing> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="parent2_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label21"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Grade:</property> + </object> + <packing> + <property name="top_attach">3</property> + <property name="bottom_attach">4</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="grade_label"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">3</property> + <property name="bottom_attach">4</property> + </packing> + </child> + </object> + <packing> + <property name="position">0</property> + </packing> </child> <child> - <placeholder/> + <object class="GtkButton" id="play_button"> + <property name="label" translatable="yes">Play</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="position">1</property> + </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkNotebook" id="generation_info_tab"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <child> <object class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="label" translatable="yes">x graifigi</property> </object> </child> <child type="tab"> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </object> <packing> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="label" translatable="yes">y grafigi</property> </object> <packing> <property name="position">1</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </object> <packing> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="label" translatable="yes">z grafigi</property> </object> <packing> <property name="position">2</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </object> <packing> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="textview1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> diff --git a/src/util/storage.py b/src/util/storage.py index 192708c..3a57805 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,198 +1,198 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 import json class db: _connection = None def __init__(self): self._connection = sqlite3.connect(SQLITE_FILE) c = self._cursor # Create neural networks table c.execute(''' CREATE TABLE IF NOT EXISTS neural_networks( name TEXT PRIMARY KEY ON CONFLICT REPLACE, dataset TEXT, trained BOOLEAN ); ''') # Create evolutions table c.execute(''' CREATE TABLE IF NOT EXISTS evolutions( name TEXT PRIMARY KEY ON CONFLICT REPLACE, population_size INTEGER, generation_count INTEGER, evaluator TEXT, - initialized BOOLEAN, + state TEXT, FOREIGN KEY(evaluator) REFERENCES neural_networks(name) ); ''') # create genomes table c.execute(''' CREATE TABLE IF NOT EXISTS genomes( name TEXT PRIMARY KEY ON CONFLICT REPLACE, genome TEXT, evolution TEXT, generation INTEGER, individual_id, parent_1 TEXT, parent_2 TEXT, grade REAL, status TEXT, FOREIGN KEY(evolution) REFERENCES evolutions(name) ); ''') self._commit() c.close() def _commit(self): self._connection.commit() @property def _cursor(self): return self._connection.cursor() def close(self): self._connection.close() - def save_evolution(self, name, population_size, evaluator, generation_count, initialized): + def save_evolution(self, name, population_size, evaluator, generation_count, state): c = self._cursor c.execute(''' - INSERT INTO evolutions (name, evaluator, population_size, generation_count, initialized) + INSERT INTO evolutions (name, evaluator, population_size, generation_count, state) VALUES(?, ?, ?, ?, ?); - ''', (name, evaluator, population_size, generation_count, int(initialized))) + ''', (name, evaluator, population_size, generation_count, state)) self._commit() c.close() return #Returns evolution for the given row id def get_evolution(self, name): c = self._cursor c.execute(''' SELECT * FROM evolutions WHERE name=? ''', [name]) result = c.fetchall() c.close() return result[0] if result else None def get_evolution_list(self): c = self._cursor c.execute(''' SELECT name FROM evolutions ''') result = c.fetchall() c.close() return result def new_neural_network(self, name, dataset): c = self._cursor c.execute(''' INSERT INTO neural_networks (name, dataset, trained) VALUES(?, ?, ?); ''', (name, json.dumps(dataset), 0)) self._commit() c.close() return def save_neural_network(self, dataset, trained): c = self._cursor c.execute(''' UPDATE neural_networks SET trained=? WHERE name=?; ''', (int(trained), json.dumps(dataset))) self._commit() c.close() return def get_neural_network(self, name): c = self._cursor c.execute(''' SELECT dataset, trained from neural_networks WHERE name=?; ''', [name]) result = c.fetchall()[0] c.close() return json.loads(result[0]), bool(result[1]) def get_neural_network_list(self): c = self._cursor c.execute(''' SELECT name FROM neural_networks ''') result = c.fetchall() c.close() return [x[0] for x in result] def get_genomes(self, evolution, generation): c = self._cursor c.execute(''' SELECT * FROM genomes WHERE evolution=? AND generation=? ORDER BY individual_id ASC ''', [evolution, generation]) result = c.fetchall() c.close() return result def save_genome(self, name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status): c = self._cursor c.execute(''' INSERT INTO genomes(name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?); ''', (name, genome, evolution, generation, individual_id, parent_1, parent_2, grade, status)) self._commit() c.close() return
cagatay/Evolution-9
b6ee347b1c5a70543b2affa569aa9a26b430c72e
bugfixes, improvemtnes, gui work
diff --git a/src/brain/NN.py b/src/brain/NN.py index 6ee0381..c175334 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,183 +1,185 @@ from pybrain.tools.shortcuts import buildNetwork from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import constants import pickle import math import random from util import rttl class neural_network(object): def __init__(self, name, dataset, trained, store): self.name = name self.store = store self.trained = True self.dataset = dataset return def save(self): - self.store.update_neural_network(self.name, self.trained) + self.store.save_neural_network(self.name, self.dataset, self.trained) return @classmethod def get_saved(cls, name, store): result = store.get_neural_network(name) return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) - print dataset store.new_neural_network(name, dataset) return def evaluate(self, genome): return random.random() + def train(self): + self.save() + ''' class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 hiddenLayerNodeCount = 20 durationPerNote = 2; ds = SupervisedDataSet(inputCount, outputCount) def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount self.durationPerNote = _durationPerNote self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) def train(self): trainer = BackpropTrainer(self.net, self.ds, verbose=True) trainer.trainUntilConvergence() # for i in range(0,5000): # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) # def addSong(self, song): song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): #sampleOutputList.append( song.intList[ z ] ) sampleOutputList.append( 1 ) self.ds.addSample( sampleList, sampleOutputList ) sampleList = list() sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 return song def fitness(self, song): returnValue = 0.0 song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 return returnValue ''' diff --git a/src/evolution/genome.py b/src/evolution/genome.py index bfc982c..421be09 100644 --- a/src/evolution/genome.py +++ b/src/evolution/genome.py @@ -1,13 +1,32 @@ from util import rttl -class Song(object): - def __init__(self, genome): - if type(genome) == 'list': +class song(object): + def __init__(self, + genome, + evolution, + generation, + individual_id, + parent_1 = '', + parent_2 = '', + grade = 0.0, + status = 'created'): + + if type(genome) is list: self.note_list = genome self.genome = rttl.dump(genome) - elif type(genome) == 'string': + elif type(genome) is unicode: self.genome = genome self.note_list = rttl.parse(genome) self.int_list = rttl.to_int(self.note_list) + + self.evolution = evolution + self.generation = generation + self.parent_1 = parent_1 + self.parent_2 = parent_2 + self.grade = grade + self.status = status + self.individual_id = individual_id + + self.name = self.evolution + '-' + str(self.generation) + '-' + str(self.individual_id) diff --git a/src/evolution/manager.py b/src/evolution/manager.py index 3db82f5..888b6c5 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,31 +1,76 @@ from brain.NN import neural_network +from evolution import operators +from evolution.genome import song class evolution(object): - def __init__(self, name, evaluator, population_size, store, initialized = False): + def __init__(self, name, evaluator, population_size, store, generation_count = 0, initialized = False): self.store = store self.name = name self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size - self.generation_count = 0 + self.generation_count = generation_count self.initialized = initialized + if initialized: + self.get_current_generation() + else: + self.current_generation = None self.save() def save(self): self.store.save_evolution(self.name, self.population_size, self.evaluator.name, self.generation_count, self.initialized) + return + + def save_genomes(self): + for g in self.current_generation: + self.store.save_genome(g.name, + g.genome, + g.evolution, + g.generation, + g.individual_id, + g.parent_1, + g.parent_2, + g.grade, + g.status) + return @classmethod def get_saved(cls, name, store): result = store.get_evolution(name) - return cls(result[1], result[2], result[3], store) if result else None + return cls(result[0], result[3], result[1], store, result[2], bool(result[4])) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() return [x[0] for x in result] if result else None + + def initialize(self): + self.current_generation = [] + + for i in xrange(self.population_size): + g = song(operators.random_genome(), self.name, 0, i) + self.current_generation.append(g) + + self.initialized = True + self.save_genomes() + self.save() + return + + def get_current_generation(self): + result = self.store.get_genomes(self.name, self.generation_count) + + if result: + self.current_generation = [] + + for i in result: + g = song(i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]) + self.current_generation.append(g) + + return + diff --git a/src/main.py b/src/main.py index 1c0a627..a7c76f8 100755 --- a/src/main.py +++ b/src/main.py @@ -1,95 +1,162 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from evolution.manager import evolution from util.storage import db class evolution9_app(object): def __init__(self): self.store = db() self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') + self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() + self.evolution_list = gtk.ListStore(str) + self.evolution_combo = self.builder.get_object('evolution_combo') + self.evolution_combo.set_model(self.evolution_list) + cell = gtk.CellRendererText() + self.evolution_combo.pack_start(cell, True) + self.evolution_combo.add_attribute(cell, 'text', 0) + + self.update_evolution_list() + + self.genome_list = gtk.ListStore(int, str) + self.genome_view = self.builder.get_object('genome_view') + self.genome_view.set_model(self.genome_list) + cell = gtk.CellRendererText() + column = gtk.TreeViewColumn('Genome', cell, text=1) + self.genome_view.append_column(column) + # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) + def start_evolution(self): + if not self.evolution9.initialized: + self.builder.get_object('initialize_button').set_sensitive(True) + self.builder.get_object('step_1_button').set_sensitive(True) + self.builder.get_object('step_50_button').set_sensitive(True) + self.builder.get_object('generation_info_tab').set_sensitive(True) + + self.update_genome_list() + def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def main(self): self.window.show() gtk.main() + def update_evolution_list(self): + self.evolution_list.clear() + evolutions = evolution.get_list(self.store) + + if evolutions: + for e in evolutions: + self.evolution_combo.append_text(e) + + return + def update_nn_list(self): self.nn_list.clear() networks = neural_network.get_list(self.store) if networks: for n in networks: self.nn_combo.append_text(n) + return + + def update_genome_list(self): + self.genome_list.clear() + l = self.evolution9.current_generation + + if l: + for x in range(len(l)): + self.genome_list.append((x, l[x].genome)) + return + def on_new_evolution_ok_button_clicked(self, *args): name = self.builder.get_object('new_evolution_name').get_text() population_size = self.builder.get_object('new_evolution_pop_size').get_text() evaluator = self.builder.get_object('nn_combo').get_active_text() try: - self.evolution9 = evolution(name, evaluator, population_size, self.store) + self.evolution9 = evolution(name, evaluator, int(population_size), self.store) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.new_evolution_dialog.hide() + self.start_evolution() def on_open_evolution_button_clicked(self, *args): - self.error_message('There is no saved evolution. You must create one first') + self.open_evolution_dialog.present() + return def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() + return + + def on_open_evolution_ok_button_clicked(self, *args): + name = self.builder.get_object('evolution_combo').get_active_text() + + try: + self.evolution9 = evolution.get_saved(name, self.store) + except Exception, err: + self.error_message(str(err)) + traceback.print_exc(file=sys.stdout) + else: + self.start_evolution() + self.open_evolution_dialog.hide() + + def on_initialize_button_clicked(self, *args): + self.evolution9.initialize() + self.builder.get_object('initialize_button').set_sensitive(False) + self.update_genome_list() if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 72ea7ac..000d916 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,797 +1,851 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> - <object class="GtkListStore" id="genome_list"/> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">800</property> <property name="default_height">600</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> - <object class="GtkButton" id="button1"> + <object class="GtkButton" id="initialize_button"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> + <signal name="clicked" handler="on_initialize_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> - <object class="GtkButton" id="button2"> + <object class="GtkButton" id="step_1_button"> <property name="label" translatable="yes">Step 1</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> - <object class="GtkButton" id="button3"> + <object class="GtkButton" id="step_50_button"> <property name="label" translatable="yes">Step 50</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> - <object class="GtkTreeView" id="treeview1"> + <object class="GtkTreeView" id="genome_view"> <property name="visible">True</property> <property name="can_focus">True</property> - <property name="model">genome_list</property> + <property name="enable_search">False</property> + <property name="ubuntu_almost_fixed_height_mode">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">9</property> <property name="n_columns">2</property> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> - <object class="GtkNotebook" id="notebook1"> + <object class="GtkNotebook" id="generation_info_tab"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <child> <object class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="label" translatable="yes">x graifigi</property> </object> </child> <child type="tab"> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </object> <packing> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="label" translatable="yes">y grafigi</property> </object> <packing> <property name="position">1</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </object> <packing> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="label" translatable="yes">z grafigi</property> </object> <packing> <property name="position">2</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </object> <packing> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="textview1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> - <object class="GtkListStore" id="evolution_list"/> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> + <object class="GtkDialog" id="open_evolution_dialog"> + <property name="border_width">5</property> + <property name="title" translatable="yes">Open evolution</property> + <property name="modal">True</property> + <property name="window_position">center-on-parent</property> + <property name="type_hint">normal</property> + <signal name="delete_event" handler="hide_dialog"/> + <child internal-child="vbox"> + <object class="GtkVBox" id="dialog-vbox4"> + <property name="visible">True</property> + <property name="orientation">vertical</property> + <property name="spacing">2</property> + <child> + <object class="GtkComboBox" id="evolution_combo"> + <property name="visible">True</property> + <property name="active">0</property> + <property name="entry_text_column">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="position">1</property> + </packing> + </child> + <child internal-child="action_area"> + <object class="GtkHButtonBox" id="dialog-action_area4"> + <property name="visible">True</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="open_evolution_ok_button"> + <property name="label" translatable="yes">OK</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_open_evolution_ok_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="0">open_evolution_ok_button</action-widget> + </action-widgets> + </object> </interface> diff --git a/src/util/music.py b/src/util/music.py index a1b5b81..e44802e 100644 --- a/src/util/music.py +++ b/src/util/music.py @@ -1,34 +1,34 @@ import random from mingus.containers.Note import Note from mingus.core import value note_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] dot_range = ['.', ''] class note(object): def __init__(self, note, octave, duration, dot): - self.note = note + self.note = str(note) self.octave = '' if octave is None else octave self.duration = duration self.dot = dot if self.note == 'P': self.mingus_note = '0' else: self.mingus_note = Note(self.note, int(self.octave)) def int_tuple(self): return (int(self.mingus_note), value.dots(int(self.duration), int(bool(self.dot)))) def __str__(self): return self.duration + self.note + self.dot + self.octave def random_note(): return note(random.choice(note_range), random.choice(octave_range), random.choice(duration_range), random.choice(dot_range)) diff --git a/src/util/rttl.py b/src/util/rttl.py index 8f3ed9f..f223ef0 100644 --- a/src/util/rttl.py +++ b/src/util/rttl.py @@ -1,65 +1,64 @@ ''' Created on 12 Ara 2010 @author: melih ''' from util.music import note def parse(rttl_string): rttl_string = rttl_string.strip() track = [] parts = rttl_string.split(":") defaults = parts[1] notes = parts[2] if defaults: defaults = defaults.split(",") defaultDuration = defaults[0].split("=")[1] defaultOctave = defaults[1].split("=")[1] notes = notes.split(",") for n in notes: n = n.strip().upper() if defaults: duration = defaultDuration octave = defaultOctave dot = '' if n[0].isdigit(): if n[1].isdigit(): duration = n[:2] n = n[2:] else: duration = n[0] n = n[1:] if n[len(n) - 1].isdigit(): octave = n[len(n) - 1] n = n[0:len(n) - 1] if n.endswith("."): dot = '.' n = n[0:len(n) - 1] track.append(note(n, duration, octave, dot)) - return track def dataset_from_file(file_uri): ds_file = file(file_uri) ds_list = [] for line in ds_file: track = parse(line) ds_list.append(to_int(track)) return ds_list def dump(note_list): out = '::' for note in note_list: out += str(note) + ',' return out.rstrip(',') def to_int(note_list): return [x.int_tuple() for x in note_list] diff --git a/src/util/storage.py b/src/util/storage.py index aa8ea8f..192708c 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,158 +1,198 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 import json class db: _connection = None def __init__(self): self._connection = sqlite3.connect(SQLITE_FILE) - c = self._connection.cursor() + c = self._cursor # Create neural networks table c.execute(''' CREATE TABLE IF NOT EXISTS neural_networks( name TEXT PRIMARY KEY ON CONFLICT REPLACE, dataset TEXT, trained BOOLEAN ); ''') - # Create saved table + # Create evolutions table c.execute(''' CREATE TABLE IF NOT EXISTS evolutions( name TEXT PRIMARY KEY ON CONFLICT REPLACE, population_size INTEGER, generation_count INTEGER, evaluator TEXT, initialized BOOLEAN, FOREIGN KEY(evaluator) REFERENCES neural_networks(name) ); ''') # create genomes table c.execute(''' CREATE TABLE IF NOT EXISTS genomes( - id INTEGER PRIMARY KEY ON CONFLICT REPLACE, + name TEXT PRIMARY KEY ON CONFLICT REPLACE, genome TEXT, evolution TEXT, - parent_1 INTEGER, - parent_2 INTEGER, + generation INTEGER, + individual_id, + parent_1 TEXT, + parent_2 TEXT, + grade REAL, status TEXT, FOREIGN KEY(evolution) REFERENCES evolutions(name) ); ''') self._commit() c.close() def _commit(self): self._connection.commit() @property def _cursor(self): return self._connection.cursor() def close(self): self._connection.close() def save_evolution(self, name, population_size, evaluator, generation_count, initialized): c = self._cursor c.execute(''' INSERT INTO evolutions (name, evaluator, population_size, generation_count, initialized) VALUES(?, ?, ?, ?, ?); ''', (name, evaluator, population_size, generation_count, int(initialized))) self._commit() c.close() return #Returns evolution for the given row id def get_evolution(self, name): - c = self._cursor() + c = self._cursor c.execute(''' SELECT * FROM evolutions WHERE name=? - ''', (name)) + ''', [name]) result = c.fetchall() c.close() return result[0] if result else None def get_evolution_list(self): - c = self._cursor() + c = self._cursor c.execute(''' SELECT name FROM evolutions ''') result = c.fetchall() c.close() return result def new_neural_network(self, name, dataset): c = self._cursor c.execute(''' INSERT INTO neural_networks (name, dataset, trained) VALUES(?, ?, ?); ''', (name, json.dumps(dataset), 0)) self._commit() c.close() return - def update_neural_network(self, row_id, trained): + def save_neural_network(self, dataset, trained): c = self._cursor c.execute(''' UPDATE neural_networks SET trained=? WHERE name=?; - ''', (int(trained), row_id)) + ''', (int(trained), json.dumps(dataset))) self._commit() c.close() return def get_neural_network(self, name): c = self._cursor c.execute(''' SELECT dataset, trained from neural_networks WHERE name=?; ''', [name]) result = c.fetchall()[0] c.close() return json.loads(result[0]), bool(result[1]) def get_neural_network_list(self): c = self._cursor c.execute(''' SELECT name FROM neural_networks ''') result = c.fetchall() c.close() return [x[0] for x in result] - #Updates status of the given row id - def update(self, rowid, status): - c = self.cursor() + def get_genomes(self, evolution, generation): + c = self._cursor + c.execute(''' + SELECT * FROM genomes WHERE evolution=? AND generation=? ORDER BY individual_id ASC + ''', [evolution, generation]) + + result = c.fetchall() + c.close() + + return result + + def save_genome(self, + name, + genome, + evolution, + generation, + individual_id, + parent_1, + parent_2, + grade, + status): + + c = self._cursor c.execute(''' - UPDATE composers SET status=? WHERE ROWID=? - ''', (status, rowid)) + INSERT INTO genomes(name, + genome, + evolution, + generation, + individual_id, + parent_1, + parent_2, + grade, + status) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?); + ''', (name, + genome, + evolution, + generation, + individual_id, + parent_1, + parent_2, + grade, + status)) - self.commit() + self._commit() c.close() return
cagatay/Evolution-9
84fc19d56d020b6f3db83889c6492ac69b71bcdf
various bugfixes, gui work
diff --git a/src/brain/NN.py b/src/brain/NN.py index cb33230..6ee0381 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,183 +1,183 @@ from pybrain.tools.shortcuts import buildNetwork from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import constants import pickle import math import random from util import rttl class neural_network(object): - def __init__(self, name, store, dataset, trained, row_id = None): + def __init__(self, name, dataset, trained, store): self.name = name self.store = store self.trained = True - - self.save() + self.dataset = dataset return def save(self): - self.store.update_neural_network(self.row_id, self.trained) + self.store.update_neural_network(self.name, self.trained) return @classmethod - def get_saved(cls, row_id, store): - result = store.get_neural_network(row_id) - - return cls(result[0], store, result[1], row_id) + def get_saved(cls, name, store): + result = store.get_neural_network(name) + + return cls(name, result[0], result[1], store) if result else None @classmethod def get_list(cls, store): result = store.get_neural_network_list() return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) + print dataset store.new_neural_network(name, dataset) return def evaluate(self, genome): return random.random() ''' class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 hiddenLayerNodeCount = 20 durationPerNote = 2; ds = SupervisedDataSet(inputCount, outputCount) def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount self.durationPerNote = _durationPerNote self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) def train(self): trainer = BackpropTrainer(self.net, self.ds, verbose=True) trainer.trainUntilConvergence() # for i in range(0,5000): # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) # def addSong(self, song): song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): #sampleOutputList.append( song.intList[ z ] ) sampleOutputList.append( 1 ) self.ds.addSample( sampleList, sampleOutputList ) sampleList = list() sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 return song def fitness(self, song): returnValue = 0.0 song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 return returnValue ''' diff --git a/src/evolution/manager.py b/src/evolution/manager.py index 2ca60e0..3db82f5 100644 --- a/src/evolution/manager.py +++ b/src/evolution/manager.py @@ -1,36 +1,31 @@ +from brain.NN import neural_network class evolution(object): - def __init__(self, name, evaluator, population_size, store, row_id): + def __init__(self, name, evaluator, population_size, store, initialized = False): self.store = store self.name = name - self.evaluator = evaluator + self.evaluator = neural_network.get_saved(evaluator, store) self.population_size = population_size self.generation_count = 0 + self.initialized = initialized - if row_id is None: - self.row_id = self.save() - else: - self.row_id = row_id + self.save() def save(self): - if self.row_id: - self.store.update_evolution(self.row_id, - self.generation_count, - self.initialized) - else: - return self.store.new_evolution(self.name, - self.evaluator, - self.population_size, - self.initialized) + self.store.save_evolution(self.name, + self.population_size, + self.evaluator.name, + self.generation_count, + self.initialized) @classmethod - def get_saved(cls, row_id, store): - result = store.get_evolution(row_id) + def get_saved(cls, name, store): + result = store.get_evolution(name) - return cls(result[1], result[2], result[3], store, row_id) if result else None + return cls(result[1], result[2], result[3], store) if result else None @classmethod def get_list(cls, store): result = store.get_evolution_list() - return [tuple(x) for x in result] if result else None + return [x[0] for x in result] if result else None diff --git a/src/main.py b/src/main.py index 8c157d8..1c0a627 100755 --- a/src/main.py +++ b/src/main.py @@ -1,79 +1,95 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network +from evolution.manager import evolution from util.storage import db class evolution9_app(object): def __init__(self): self.store = db() self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') self.nn_list = gtk.ListStore(str) self.nn_combo = self.builder.get_object('nn_combo') self.nn_combo.set_model(self.nn_list) cell = gtk.CellRendererText() self.nn_combo.pack_start(cell, True) self.nn_combo.add_attribute(cell,'text', 0) self.update_nn_list() # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def main(self): self.window.show() gtk.main() def update_nn_list(self): + self.nn_list.clear() networks = neural_network.get_list(self.store) - for n in networks: - self.nn_combo.append_text(n) + if networks: + for n in networks: + self.nn_combo.append_text(n) + + def on_new_evolution_ok_button_clicked(self, *args): + name = self.builder.get_object('new_evolution_name').get_text() + population_size = self.builder.get_object('new_evolution_pop_size').get_text() + evaluator = self.builder.get_object('nn_combo').get_active_text() + + try: + self.evolution9 = evolution(name, evaluator, population_size, self.store) + except Exception, err: + self.error_message(str(err)) + traceback.print_exc(file=sys.stdout) + else: + self.new_evolution_dialog.hide() def on_open_evolution_button_clicked(self, *args): self.error_message('There is no saved evolution. You must create one first') def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 12bc971..72ea7ac 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,797 +1,797 @@ <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkListStore" id="genome_list"/> <object class="GtkWindow" id="window"> <property name="width_request">600</property> <property name="height_request">400</property> <property name="title" translatable="yes">Evolution-9</property> <property name="window_position">center</property> <property name="default_width">800</property> <property name="default_height">600</property> <signal name="destroy" handler="on_window_destroy"/> <child> <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> <property name="layout_style">start</property> <child> <object class="GtkButton" id="new_evolution_button"> <property name="label" translatable="yes">New Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="open_evolution_button"> <property name="label" translatable="yes">Open Evolution</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_open_evolution_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> <child> <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="border_width">10</property> <property name="orientation">vertical</property> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="button1"> <property name="label" translatable="yes">Initialize</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="button2"> <property name="label" translatable="yes">Step 1</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="button3"> <property name="label" translatable="yes">Step 50</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTreeView" id="treeview1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="model">genome_list</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkVBox" id="vbox4"> <property name="width_request">300</property> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="homogeneous">True</property> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkTable" id="table1"> <property name="visible">True</property> <property name="n_rows">9</property> <property name="n_columns">2</property> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Individual Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frame2"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <child> <object class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="label" translatable="yes">x graifigi</property> </object> </child> <child type="tab"> <object class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </object> <packing> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="label" translatable="yes">y grafigi</property> </object> <packing> <property name="position">1</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </object> <packing> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="label" translatable="yes">z grafigi</property> </object> <packing> <property name="position">2</property> </packing> </child> <child type="tab"> <object class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </object> <packing> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Generation Information</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> <child> <object class="GtkFrame" id="frame3"> <property name="visible">True</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">automatic</property> <property name="vscrollbar_policy">automatic</property> <child> <object class="GtkTextView" id="textview1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="cursor_visible">False</property> </object> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="label" translatable="yes">Console</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="resize">True</property> <property name="shrink">True</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> </object> </child> </object> <object class="GtkListStore" id="evolution_list"/> <object class="GtkDialog" id="new_neural_network_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New neural network</property> <property name="modal">True</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox2"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkTable" id="table3"> <property name="visible">True</property> <property name="n_rows">2</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label16"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> <object class="GtkEntry" id="new_nn_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label17"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Dataset:</property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkFileChooserButton" id="new_nn_dataset_file"> <property name="visible">True</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area2"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <object class="GtkButton" id="new_neural_network_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> <action-widget response="0">new_neural_network_ok_button</action-widget> </action-widgets> </object> <object class="GtkDialog" id="new_evolution_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">New evolution</property> <property name="modal">True</property> <property name="window_position">center-on-parent</property> <property name="type_hint">normal</property> <signal name="delete_event" handler="hide_dialog"/> <child internal-child="vbox"> <object class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkTable" id="table2"> <property name="visible">True</property> <property name="n_rows">5</property> <property name="n_columns">2</property> <child> <object class="GtkLabel" id="label10"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Name:</property> </object> </child> <child> - <object class="GtkEntry" id="entry1"> + <object class="GtkEntry" id="new_evolution_name"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label11"> <property name="visible">True</property> <property name="xalign">0</property> - <property name="label" translatable="yes">Population Count: </property> + <property name="label" translatable="yes">Population Size: </property> </object> <packing> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> - <object class="GtkEntry" id="entry2"> + <object class="GtkEntry" id="new_evolution_pop_size"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x2022;</property> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">1</property> <property name="bottom_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">0</property> <property name="label" translatable="yes">Mutator Types:</property> </object> <packing> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton1"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton2"> <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton3"> <property name="label" translatable="yes">Replace</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton4"> <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton5"> <property name="label" translatable="yes">Inversion</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">4</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">2</property> <property name="bottom_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label13"> <property name="visible">True</property> <property name="xalign">0</property> <property name="yalign">2.2351741291171123e-10</property> <property name="label" translatable="yes">Crossover Types:</property> </object> <packing> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkCheckButton" id="checkbutton6"> <property name="label" translatable="yes">Random</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton7"> <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton8"> <property name="label" translatable="yes">Two Point</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="checkbutton9"> <property name="label" translatable="yes">Uniform</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="draw_indicator">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">3</property> <property name="bottom_attach">4</property> </packing> </child> <child> <object class="GtkLabel" id="label14"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Evaluator</property> </object> <packing> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkComboBox" id="nn_combo"> <property name="visible">True</property> <property name="active">0</property> <property name="entry_text_column">0</property> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="new_neural_network_button2"> <property name="label" translatable="yes">New</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_new_neural_network_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">1</property> <property name="right_attach">2</property> <property name="top_attach">4</property> <property name="bottom_attach">5</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkLabel" id="label15"> <property name="visible">True</property> <property name="xalign">0</property> <property name="justify">right</property> </object> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <object class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="layout_style">end</property> <child> - <object class="GtkButton" id="button7"> + <object class="GtkButton" id="new_evolution_ok_button"> <property name="label" translatable="yes">OK</property> <property name="visible">True</property> - <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> + <signal name="clicked" handler="on_new_evolution_ok_button_clicked"/> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </object> </child> <action-widgets> - <action-widget response="0">button7</action-widget> + <action-widget response="0">new_evolution_ok_button</action-widget> </action-widgets> </object> </interface> diff --git a/src/util/rttl.py b/src/util/rttl.py index f425dd2..8f3ed9f 100644 --- a/src/util/rttl.py +++ b/src/util/rttl.py @@ -1,63 +1,65 @@ ''' Created on 12 Ara 2010 @author: melih ''' from util.music import note def parse(rttl_string): rttl_string = rttl_string.strip() track = [] parts = rttl_string.split(":") defaults = parts[1] notes = parts[2] if defaults: defaults = defaults.split(",") defaultDuration = defaults[0].split("=")[1] defaultOctave = defaults[1].split("=")[1] notes = notes.split(",") for n in notes: n = n.strip().upper() if defaults: duration = defaultDuration octave = defaultOctave dot = '' if n[0].isdigit(): if n[1].isdigit(): duration = n[:2] n = n[2:] else: duration = n[0] n = n[1:] if n[len(n) - 1].isdigit(): octave = n[len(n) - 1] n = n[0:len(n) - 1] if n.endswith("."): dot = '.' n = n[0:len(n) - 1] track.append(note(n, duration, octave, dot)) return track def dataset_from_file(file_uri): ds_file = file(file_uri) ds_list = [] for line in ds_file: track = parse(line) ds_list.append(to_int(track)) + return ds_list + def dump(note_list): out = '::' for note in note_list: out += str(note) + ',' return out.rstrip(',') def to_int(note_list): return [x.int_tuple() for x in note_list] diff --git a/src/util/storage.py b/src/util/storage.py index f2a6de2..aa8ea8f 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,157 +1,158 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 -import pickle +import json class db: _connection = None def __init__(self): self._connection = sqlite3.connect(SQLITE_FILE) c = self._connection.cursor() # Create neural networks table c.execute(''' CREATE TABLE IF NOT EXISTS neural_networks( - name TEXT PRIMARY KEY, + name TEXT PRIMARY KEY ON CONFLICT REPLACE, dataset TEXT, trained BOOLEAN ); ''') # Create saved table c.execute(''' CREATE TABLE IF NOT EXISTS evolutions( - name TEXT PRIMARY KEY, + name TEXT PRIMARY KEY ON CONFLICT REPLACE, population_size INTEGER, generation_count INTEGER, evaluator TEXT, initialized BOOLEAN, FOREIGN KEY(evaluator) REFERENCES neural_networks(name) ); ''') # create genomes table c.execute(''' CREATE TABLE IF NOT EXISTS genomes( - id INTEGER PRIMARY KEY, + id INTEGER PRIMARY KEY ON CONFLICT REPLACE, genome TEXT, evolution TEXT, parent_1 INTEGER, parent_2 INTEGER, status TEXT, FOREIGN KEY(evolution) REFERENCES evolutions(name) ); ''') self._commit() c.close() def _commit(self): self._connection.commit() @property def _cursor(self): return self._connection.cursor() def close(self): self._connection.close() def save_evolution(self, name, population_size, evaluator, generation_count, initialized): c = self._cursor c.execute(''' INSERT INTO evolutions (name, evaluator, population_size, generation_count, initialized) - VALUES(?, ?, ?, ?); + VALUES(?, ?, ?, ?, ?); ''', (name, evaluator, population_size, generation_count, int(initialized))) self._commit() c.close() return - def update_evolution(self, row_id, generation_count, initialized): - c = self._cursor - - c.execute(''' - UPDATE evolutions SET generation_count=?, initialized=? WHERE id=?; - ''', (generation_count, int(initialized), row_id)) - - self._commit() - c.close() - - return - #Returns evolution for the given row id - def get_evolution(self, rowid): + def get_evolution(self, name): c = self._cursor() c.execute(''' - SELECT * FROM evolutions WHERE id=? - ''', (rowid)) + SELECT * FROM evolutions WHERE name=? + ''', (name)) result = c.fetchall() c.close() return result[0] if result else None def get_evolution_list(self): c = self._cursor() c.execute(''' - SELECT * FROM evolutions + SELECT name FROM evolutions ''') result = c.fetchall() c.close() return result def new_neural_network(self, name, dataset): c = self._cursor c.execute(''' INSERT INTO neural_networks (name, dataset, trained) VALUES(?, ?, ?); - ''', (name, pickle.dumps(dataset), 0)) + ''', (name, json.dumps(dataset), 0)) self._commit() c.close() return def update_neural_network(self, row_id, trained): c = self._cursor c.execute(''' UPDATE neural_networks SET trained=? WHERE name=?; ''', (int(trained), row_id)) self._commit() c.close() return + def get_neural_network(self, name): + c = self._cursor + + c.execute(''' + SELECT dataset, trained from neural_networks WHERE name=?; + ''', [name]) + + result = c.fetchall()[0] + + c.close() + + return json.loads(result[0]), bool(result[1]) + def get_neural_network_list(self): c = self._cursor c.execute(''' SELECT name FROM neural_networks ''') result = c.fetchall() c.close() return [x[0] for x in result] #Updates status of the given row id def update(self, rowid, status): c = self.cursor() c.execute(''' UPDATE composers SET status=? WHERE ROWID=? ''', (status, rowid)) self.commit() c.close() return
cagatay/Evolution-9
65c698badb2049167376160ce8b708a56384b96c
gui development
diff --git a/.gitignore b/.gitignore index b8b7417..94e4bd4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ +data/* output/* midi/* *.pyc *.swp diff --git a/README.txt b/README.txt index c80ccf0..4103170 100644 --- a/README.txt +++ b/README.txt @@ -1,11 +1,12 @@ requirements: python 2.6 (strictly) pybrain (and its own requirements) mingus pyevolve + pygtk installation: python 2.6 http://www.python.org/download pybrain http://pybrain.org/pages/download (make sure that you installed SciPy and Numpy) mingus http://code.google.com/p/mingus/downloads/list pyevolve http://pyevolve.sourceforge.net/intro.html#downloads diff --git a/data/evolution9.db b/data/evolution9.db index a95600c..eb3f777 100644 Binary files a/data/evolution9.db and b/data/evolution9.db differ diff --git a/src/brain/NN.py b/src/brain/NN.py index 583f794..cb33230 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,186 +1,183 @@ from pybrain.tools.shortcuts import buildNetwork from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import constants import pickle import math import random from util import rttl class neural_network(object): def __init__(self, name, store, dataset, trained, row_id = None): self.name = name self.store = store self.trained = True - if row_id is None: - self.row_id = self.save() - else: - self.row_id = row_id + self.save() return def save(self): self.store.update_neural_network(self.row_id, self.trained) return @classmethod def get_saved(cls, row_id, store): result = store.get_neural_network(row_id) return cls(result[0], store, result[1], row_id) @classmethod def get_list(cls, store): result = store.get_neural_network_list() - return [tuple(x) for x in result] + return [x for x in result] @classmethod def new(cls, name, store, ds_file_uri): dataset = rttl.dataset_from_file(ds_file_uri) store.new_neural_network(name, dataset) return def evaluate(self, genome): return random.random() ''' class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 hiddenLayerNodeCount = 20 durationPerNote = 2; ds = SupervisedDataSet(inputCount, outputCount) def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount self.durationPerNote = _durationPerNote self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) def train(self): trainer = BackpropTrainer(self.net, self.ds, verbose=True) trainer.trainUntilConvergence() # for i in range(0,5000): # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) # def addSong(self, song): song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): #sampleOutputList.append( song.intList[ z ] ) sampleOutputList.append( 1 ) self.ds.addSample( sampleList, sampleOutputList ) sampleList = list() sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 return song def fitness(self, song): returnValue = 0.0 song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 return returnValue ''' diff --git a/src/main.py b/src/main.py index 84fcb33..8c157d8 100755 --- a/src/main.py +++ b/src/main.py @@ -1,62 +1,79 @@ #!/usr/bin/python2.6 import sys, traceback import gtk from brain.NN import neural_network from util.storage import db class evolution9_app(object): def __init__(self): self.store = db() self.builder = gtk.Builder() self.builder.add_from_file('res/gui.glade') self.window = self.builder.get_object('window') self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') + + + self.nn_list = gtk.ListStore(str) + self.nn_combo = self.builder.get_object('nn_combo') + self.nn_combo.set_model(self.nn_list) + cell = gtk.CellRendererText() + self.nn_combo.pack_start(cell, True) + self.nn_combo.add_attribute(cell,'text', 0) + + self.update_nn_list() # hide dialogs instead of destroying them for reuse self.hide_dialog = gtk.Widget.hide_on_delete self.builder.connect_signals(self) def error_message(self, message): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) dialog.run() dialog.destroy() def on_window_destroy(self, widget, data = None): gtk.main_quit() def main(self): self.window.show() gtk.main() + def update_nn_list(self): + networks = neural_network.get_list(self.store) + + for n in networks: + self.nn_combo.append_text(n) + def on_open_evolution_button_clicked(self, *args): self.error_message('There is no saved evolution. You must create one first') def on_new_neural_network_button_clicked(self, *args): self.new_neural_network_dialog.present() def on_new_neural_network_ok_button_clicked(self, *args): nn_name = self.builder.get_object('new_nn_name').get_text() ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() try: neural_network.new(nn_name, self.store, ds_file_uri) except Exception, err: self.error_message(str(err)) traceback.print_exc(file=sys.stdout) else: + self.update_nn_list() self.new_neural_network_dialog.hide() def on_new_evolution_button_clicked(self, *args): self.new_evolution_dialog.present() if __name__ == '__main__': app = evolution9_app() app.main() diff --git a/src/res/gui.glade b/src/res/gui.glade index 448fc21..12bc971 100644 --- a/src/res/gui.glade +++ b/src/res/gui.glade @@ -1,178 +1,797 @@ -<?xml version="1.0" encoding="UTF-8"?> +<?xml version="1.0"?> <interface> - <requires lib="gtk+" version="2.24"/> + <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> - <object class="GtkListStore" id="liststore1"/> - <object class="GtkWindow" id="window1"> - <property name="can_focus">False</property> - <property name="title" translatable="yes">Evolution 9</property> - <property name="default_width">600</property> - <property name="default_height">400</property> - <signal name="destroy" handler="gtk_main_quit" swapped="no"/> + <object class="GtkListStore" id="genome_list"/> + <object class="GtkWindow" id="window"> + <property name="width_request">600</property> + <property name="height_request">400</property> + <property name="title" translatable="yes">Evolution-9</property> + <property name="window_position">center</property> + <property name="default_width">800</property> + <property name="default_height">600</property> + <signal name="destroy" handler="on_window_destroy"/> <child> - <object class="GtkVBox" id="vbox1"> + <object class="GtkVBox" id="vbox2"> <property name="visible">True</property> - <property name="can_focus">False</property> + <property name="orientation">vertical</property> <child> - <object class="GtkToolbar" id="toolbar1"> - <property name="height_request">40</property> + <object class="GtkHButtonBox" id="hbuttonbox2"> <property name="visible">True</property> - <property name="can_focus">False</property> + <property name="layout_style">start</property> + <child> + <object class="GtkButton" id="new_evolution_button"> + <property name="label" translatable="yes">New Evolution</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_new_evolution_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="open_evolution_button"> + <property name="label" translatable="yes">Open Evolution</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_open_evolution_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">1</property> + </packing> + </child> </object> <packing> <property name="expand">False</property> - <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> - <object class="GtkHBox" id="hbox1"> + <object class="GtkVPaned" id="vpaned1"> <property name="visible">True</property> - <property name="can_focus">False</property> + <property name="can_focus">True</property> + <property name="orientation">vertical</property> <child> - <object class="GtkVBox" id="vbox3"> + <object class="GtkHBox" id="hbox1"> <property name="visible">True</property> - <property name="can_focus">False</property> <child> - <object class="GtkHButtonBox" id="hbuttonbox1"> + <object class="GtkVBox" id="vbox3"> <property name="visible">True</property> - <property name="can_focus">False</property> + <property name="border_width">10</property> + <property name="orientation">vertical</property> <child> - <object class="GtkButton" id="button1"> - <property name="label" translatable="yes">Play</property> + <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> - <property name="can_focus">True</property> - <property name="receives_default">True</property> - <property name="use_action_appearance">False</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="button1"> + <property name="label" translatable="yes">Initialize</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="button2"> + <property name="label" translatable="yes">Step 1</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="button3"> + <property name="label" translatable="yes">Step 50</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">2</property> + </packing> + </child> </object> <packing> <property name="expand">False</property> - <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> - <object class="GtkButton" id="button2"> - <property name="label" translatable="yes">FastForward</property> + <object class="GtkScrolledWindow" id="scrolledwindow1"> <property name="visible">True</property> <property name="can_focus">True</property> - <property name="receives_default">True</property> - <property name="use_action_appearance">False</property> + <property name="hscrollbar_policy">automatic</property> + <property name="vscrollbar_policy">automatic</property> + <child> + <object class="GtkTreeView" id="treeview1"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="model">genome_list</property> + </object> + </child> </object> <packing> - <property name="expand">False</property> - <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> - <property name="expand">False</property> - <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> - <object class="GtkScrolledWindow" id="scrolledwindow1"> + <object class="GtkVBox" id="vbox4"> + <property name="width_request">300</property> <property name="visible">True</property> - <property name="can_focus">True</property> - <property name="hscrollbar_policy">automatic</property> - <property name="vscrollbar_policy">automatic</property> + <property name="orientation">vertical</property> + <property name="homogeneous">True</property> <child> - <object class="GtkTreeView" id="treeview2"> + <object class="GtkFrame" id="frame1"> <property name="visible">True</property> - <property name="can_focus">True</property> - <property name="model">liststore1</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment1"> + <property name="visible">True</property> + <property name="left_padding">12</property> + <child> + <object class="GtkTable" id="table1"> + <property name="visible">True</property> + <property name="n_rows">9</property> + <property name="n_columns">2</property> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label1"> + <property name="visible">True</property> + <property name="label" translatable="yes">Individual Information</property> + <property name="use_markup">True</property> + </object> + </child> </object> + <packing> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="frame2"> + <property name="visible">True</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment2"> + <property name="visible">True</property> + <property name="left_padding">12</property> + <child> + <object class="GtkNotebook" id="notebook1"> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <child> + <object class="GtkLabel" id="label6"> + <property name="visible">True</property> + <property name="label" translatable="yes">x graifigi</property> + </object> + </child> + <child type="tab"> + <object class="GtkLabel" id="label3"> + <property name="visible">True</property> + <property name="label" translatable="yes">page 1</property> + </object> + <packing> + <property name="tab_fill">False</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label7"> + <property name="visible">True</property> + <property name="label" translatable="yes">y grafigi</property> + </object> + <packing> + <property name="position">1</property> + </packing> + </child> + <child type="tab"> + <object class="GtkLabel" id="label4"> + <property name="visible">True</property> + <property name="label" translatable="yes">page 2</property> + </object> + <packing> + <property name="position">1</property> + <property name="tab_fill">False</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label8"> + <property name="visible">True</property> + <property name="label" translatable="yes">z grafigi</property> + </object> + <packing> + <property name="position">2</property> + </packing> + </child> + <child type="tab"> + <object class="GtkLabel" id="label5"> + <property name="visible">True</property> + <property name="label" translatable="yes">page 3</property> + </object> + <packing> + <property name="position">2</property> + <property name="tab_fill">False</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label2"> + <property name="visible">True</property> + <property name="label" translatable="yes">Generation Information</property> + <property name="use_markup">True</property> + </object> + </child> + </object> + <packing> + <property name="position">1</property> + </packing> </child> </object> <packing> - <property name="expand">True</property> - <property name="fill">True</property> + <property name="expand">False</property> + <property name="fill">False</property> <property name="position">1</property> </packing> </child> </object> <packing> - <property name="expand">True</property> - <property name="fill">True</property> + <property name="resize">True</property> + <property name="shrink">True</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="frame3"> + <property name="visible">True</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment3"> + <property name="visible">True</property> + <property name="left_padding">12</property> + <child> + <object class="GtkScrolledWindow" id="scrolledwindow2"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hscrollbar_policy">automatic</property> + <property name="vscrollbar_policy">automatic</property> + <child> + <object class="GtkTextView" id="textview1"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="cursor_visible">False</property> + </object> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label9"> + <property name="visible">True</property> + <property name="label" translatable="yes">Console</property> + <property name="use_markup">True</property> + </object> + </child> + </object> + <packing> + <property name="resize">True</property> + <property name="shrink">True</property> + </packing> + </child> + </object> + <packing> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + </object> + <object class="GtkListStore" id="evolution_list"/> + <object class="GtkDialog" id="new_neural_network_dialog"> + <property name="border_width">5</property> + <property name="title" translatable="yes">New neural network</property> + <property name="modal">True</property> + <property name="type_hint">normal</property> + <signal name="delete_event" handler="hide_dialog"/> + <child internal-child="vbox"> + <object class="GtkVBox" id="dialog-vbox2"> + <property name="visible">True</property> + <property name="orientation">vertical</property> + <property name="spacing">2</property> + <child> + <object class="GtkTable" id="table3"> + <property name="visible">True</property> + <property name="n_rows">2</property> + <property name="n_columns">2</property> + <child> + <object class="GtkLabel" id="label16"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Name:</property> + </object> + </child> + <child> + <object class="GtkEntry" id="new_nn_name"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="invisible_char">&#x2022;</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label17"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Dataset:</property> + </object> + <packing> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + </packing> + </child> + <child> + <object class="GtkFileChooserButton" id="new_nn_dataset_file"> + <property name="visible">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="position">1</property> + </packing> + </child> + <child internal-child="action_area"> + <object class="GtkHButtonBox" id="dialog-action_area2"> + <property name="visible">True</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="new_neural_network_ok_button"> + <property name="label" translatable="yes">OK</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_new_neural_network_ok_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> <property name="position">0</property> </packing> </child> + </object> + <packing> + <property name="expand">False</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="0">new_neural_network_ok_button</action-widget> + </action-widgets> + </object> + <object class="GtkDialog" id="new_evolution_dialog"> + <property name="border_width">5</property> + <property name="title" translatable="yes">New evolution</property> + <property name="modal">True</property> + <property name="window_position">center-on-parent</property> + <property name="type_hint">normal</property> + <signal name="delete_event" handler="hide_dialog"/> + <child internal-child="vbox"> + <object class="GtkVBox" id="dialog-vbox1"> + <property name="visible">True</property> + <property name="orientation">vertical</property> + <property name="spacing">2</property> + <child> + <object class="GtkVBox" id="vbox1"> + <property name="visible">True</property> + <property name="orientation">vertical</property> <child> - <object class="GtkVBox" id="vbox4"> + <object class="GtkTable" id="table2"> <property name="visible">True</property> - <property name="can_focus">False</property> + <property name="n_rows">5</property> + <property name="n_columns">2</property> <child> - <placeholder/> + <object class="GtkLabel" id="label10"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Name:</property> + </object> + </child> + <child> + <object class="GtkEntry" id="entry1"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="invisible_char">&#x2022;</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label11"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Population Count: </property> + </object> + <packing> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + </packing> </child> <child> - <object class="GtkNotebook" id="notebook1"> + <object class="GtkEntry" id="entry2"> <property name="visible">True</property> <property name="can_focus">True</property> + <property name="invisible_char">&#x2022;</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label12"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">0</property> + <property name="label" translatable="yes">Mutator Types:</property> + </object> + <packing> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + </packing> + </child> + <child> + <object class="GtkVBox" id="vbox5"> + <property name="visible">True</property> + <property name="orientation">vertical</property> <child> - <placeholder/> + <object class="GtkCheckButton" id="checkbutton1"> + <property name="label" translatable="yes">Random</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="position">0</property> + </packing> </child> - <child type="tab"> - <object class="GtkLabel" id="label1"> + <child> + <object class="GtkCheckButton" id="checkbutton2"> + <property name="label" translatable="yes">Swap</property> <property name="visible">True</property> - <property name="can_focus">False</property> - <property name="label" translatable="yes">page 1</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> </object> <packing> - <property name="tab_fill">False</property> + <property name="position">1</property> </packing> </child> <child> - <placeholder/> + <object class="GtkCheckButton" id="checkbutton3"> + <property name="label" translatable="yes">Replace</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="position">2</property> + </packing> </child> - <child type="tab"> - <object class="GtkLabel" id="label2"> + <child> + <object class="GtkCheckButton" id="checkbutton4"> + <property name="label" translatable="yes">Scramble</property> <property name="visible">True</property> - <property name="can_focus">False</property> - <property name="label" translatable="yes">page 2</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> </object> <packing> - <property name="position">1</property> - <property name="tab_fill">False</property> + <property name="position">3</property> + </packing> + </child> + <child> + <object class="GtkCheckButton" id="checkbutton5"> + <property name="label" translatable="yes">Inversion</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="position">4</property> </packing> </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label13"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="yalign">2.2351741291171123e-10</property> + <property name="label" translatable="yes">Crossover Types:</property> + </object> + <packing> + <property name="top_attach">3</property> + <property name="bottom_attach">4</property> + </packing> + </child> + <child> + <object class="GtkVBox" id="vbox6"> + <property name="visible">True</property> + <property name="orientation">vertical</property> <child> - <placeholder/> + <object class="GtkCheckButton" id="checkbutton6"> + <property name="label" translatable="yes">Random</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="position">0</property> + </packing> </child> - <child type="tab"> - <object class="GtkLabel" id="label3"> + <child> + <object class="GtkCheckButton" id="checkbutton7"> + <property name="label" translatable="yes">One Point</property> <property name="visible">True</property> - <property name="can_focus">False</property> - <property name="label" translatable="yes">page 3</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkCheckButton" id="checkbutton8"> + <property name="label" translatable="yes">Two Point</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> </object> <packing> <property name="position">2</property> - <property name="tab_fill">False</property> + </packing> + </child> + <child> + <object class="GtkCheckButton" id="checkbutton9"> + <property name="label" translatable="yes">Uniform</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="position">3</property> </packing> </child> </object> <packing> - <property name="expand">True</property> - <property name="fill">True</property> - <property name="position">1</property> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">3</property> + <property name="bottom_attach">4</property> </packing> </child> + <child> + <object class="GtkLabel" id="label14"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Evaluator</property> + </object> + <packing> + <property name="top_attach">4</property> + <property name="bottom_attach">5</property> + </packing> + </child> + <child> + <object class="GtkHBox" id="hbox2"> + <property name="visible">True</property> + <child> + <object class="GtkComboBox" id="nn_combo"> + <property name="visible">True</property> + <property name="active">0</property> + <property name="entry_text_column">0</property> + </object> + <packing> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="new_neural_network_button2"> + <property name="label" translatable="yes">New</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <signal name="clicked" handler="on_new_neural_network_button_clicked"/> + </object> + <packing> + <property name="expand">False</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">4</property> + <property name="bottom_attach">5</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label15"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="justify">right</property> </object> <packing> - <property name="expand">True</property> - <property name="fill">True</property> + <property name="expand">False</property> <property name="position">1</property> </packing> </child> </object> <packing> - <property name="expand">True</property> - <property name="fill">True</property> <property name="position">1</property> </packing> </child> + <child internal-child="action_area"> + <object class="GtkHButtonBox" id="dialog-action_area1"> + <property name="visible">True</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="button7"> + <property name="label" translatable="yes">OK</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> </object> </child> + <action-widgets> + <action-widget response="0">button7</action-widget> + </action-widgets> </object> </interface> diff --git a/src/util/storage.py b/src/util/storage.py index 3c87370..f2a6de2 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,164 +1,157 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 import pickle class db: _connection = None def __init__(self): self._connection = sqlite3.connect(SQLITE_FILE) c = self._connection.cursor() # Create neural networks table c.execute(''' CREATE TABLE IF NOT EXISTS neural_networks( - id INTEGER PRIMARY KEY, - name TEXT, + name TEXT PRIMARY KEY, dataset TEXT, trained BOOLEAN ); ''') # Create saved table c.execute(''' CREATE TABLE IF NOT EXISTS evolutions( - id INTEGER PRIMARY KEY, - name TEXT, + name TEXT PRIMARY KEY, population_size INTEGER, generation_count INTEGER, - evaluator INTEGER, + evaluator TEXT, initialized BOOLEAN, - FOREIGN KEY(evaluator) REFERENCES neural_networks(id) + FOREIGN KEY(evaluator) REFERENCES neural_networks(name) ); ''') # create genomes table c.execute(''' CREATE TABLE IF NOT EXISTS genomes( id INTEGER PRIMARY KEY, genome TEXT, - evolution_id INTEGER, + evolution TEXT, parent_1 INTEGER, parent_2 INTEGER, status TEXT, - FOREIGN KEY(evolution_id) REFERENCES evolutions(id) + FOREIGN KEY(evolution) REFERENCES evolutions(name) ); ''') self._commit() c.close() def _commit(self): self._connection.commit() @property def _cursor(self): return self._connection.cursor() def close(self): self._connection.close() def save_evolution(self, name, population_size, evaluator, generation_count, initialized): c = self._cursor c.execute(''' INSERT INTO evolutions (name, evaluator, population_size, generation_count, initialized) VALUES(?, ?, ?, ?); ''', (name, evaluator, population_size, generation_count, int(initialized))) self._commit() - c.execute(''' - SELECT id FROM evolutions ORDER BY ROWID DESC LIMIT 1 - ''') - rowid = c.fetchall() - c.close() - return rowid[0][0] + return def update_evolution(self, row_id, generation_count, initialized): c = self._cursor c.execute(''' UPDATE evolutions SET generation_count=?, initialized=? WHERE id=?; ''', (generation_count, int(initialized), row_id)) self._commit() c.close() return #Returns evolution for the given row id def get_evolution(self, rowid): c = self._cursor() c.execute(''' SELECT * FROM evolutions WHERE id=? ''', (rowid)) result = c.fetchall() c.close() return result[0] if result else None def get_evolution_list(self): c = self._cursor() c.execute(''' SELECT * FROM evolutions ''') result = c.fetchall() c.close() return result def new_neural_network(self, name, dataset): c = self._cursor c.execute(''' INSERT INTO neural_networks (name, dataset, trained) VALUES(?, ?, ?); ''', (name, pickle.dumps(dataset), 0)) self._commit() c.close() return def update_neural_network(self, row_id, trained): c = self._cursor c.execute(''' - UPDATE neural_networks SET trained=? WHERE id=?; + UPDATE neural_networks SET trained=? WHERE name=?; ''', (int(trained), row_id)) self._commit() c.close() return def get_neural_network_list(self): - c = self._cursor() + c = self._cursor c.execute(''' - SELECT * FROM neural_networks + SELECT name FROM neural_networks ''') result = c.fetchall() c.close() - return result + return [x[0] for x in result] #Updates status of the given row id def update(self, rowid, status): c = self.cursor() c.execute(''' UPDATE composers SET status=? WHERE ROWID=? ''', (status, rowid)) self.commit() c.close() return
cagatay/Evolution-9
75a027b3abacf2dea661e47e9c1114a8f20a267e
various bugfixes, gui
diff --git a/.gitignore b/.gitignore index 49ff695..b8b7417 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ output/* +midi/* *.pyc *.swp diff --git a/data/evolution9.db b/data/evolution9.db index 5545057..a95600c 100644 Binary files a/data/evolution9.db and b/data/evolution9.db differ diff --git a/src/brain/NN.py b/src/brain/NN.py index df817cc..583f794 100644 --- a/src/brain/NN.py +++ b/src/brain/NN.py @@ -1,144 +1,186 @@ from pybrain.tools.shortcuts import buildNetwork from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import constants import pickle import math +import random +from util import rttl - +class neural_network(object): + def __init__(self, name, store, dataset, trained, row_id = None): + self.name = name + self.store = store + self.trained = True + + if row_id is None: + self.row_id = self.save() + else: + self.row_id = row_id + + return + + def save(self): + self.store.update_neural_network(self.row_id, self.trained) + return + + @classmethod + def get_saved(cls, row_id, store): + result = store.get_neural_network(row_id) + + return cls(result[0], store, result[1], row_id) + + @classmethod + def get_list(cls, store): + result = store.get_neural_network_list() + + return [tuple(x) for x in result] + + @classmethod + def new(cls, name, store, ds_file_uri): + dataset = rttl.dataset_from_file(ds_file_uri) + + store.new_neural_network(name, dataset) + return + + def evaluate(self, genome): + return random.random() + +''' class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 hiddenLayerNodeCount = 20 durationPerNote = 2; ds = SupervisedDataSet(inputCount, outputCount) def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount self.durationPerNote = _durationPerNote self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) def train(self): trainer = BackpropTrainer(self.net, self.ds, verbose=True) trainer.trainUntilConvergence() # for i in range(0,5000): # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) # def addSong(self, song): song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): #sampleOutputList.append( song.intList[ z ] ) sampleOutputList.append( 1 ) self.ds.addSample( sampleList, sampleOutputList ) sampleList = list() sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 return song def fitness(self, song): returnValue = 0.0 song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 return returnValue +''' diff --git a/src/evolution/manager.py b/src/evolution/manager.py new file mode 100644 index 0000000..2ca60e0 --- /dev/null +++ b/src/evolution/manager.py @@ -0,0 +1,36 @@ + +class evolution(object): + def __init__(self, name, evaluator, population_size, store, row_id): + self.store = store + self.name = name + self.evaluator = evaluator + self.population_size = population_size + self.generation_count = 0 + + if row_id is None: + self.row_id = self.save() + else: + self.row_id = row_id + + def save(self): + if self.row_id: + self.store.update_evolution(self.row_id, + self.generation_count, + self.initialized) + else: + return self.store.new_evolution(self.name, + self.evaluator, + self.population_size, + self.initialized) + + @classmethod + def get_saved(cls, row_id, store): + result = store.get_evolution(row_id) + + return cls(result[1], result[2], result[3], store, row_id) if result else None + + @classmethod + def get_list(cls, store): + result = store.get_evolution_list() + + return [tuple(x) for x in result] if result else None diff --git a/src/main.py b/src/main.py index 906c49e..84fcb33 100755 --- a/src/main.py +++ b/src/main.py @@ -1,12 +1,62 @@ #!/usr/bin/python2.6 +import sys, traceback import gtk +from brain.NN import neural_network +from util.storage import db -def main(): - builder = gtk.Builder() - builder.add_from_file('res/gui.glade') - window = builder.get_object('window') - window.show() - gtk.main() +class evolution9_app(object): + def __init__(self): + self.store = db() + self.builder = gtk.Builder() + self.builder.add_from_file('res/gui.glade') + + self.window = self.builder.get_object('window') + self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog') + self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog') + + # hide dialogs instead of destroying them for reuse + self.hide_dialog = gtk.Widget.hide_on_delete + + self.builder.connect_signals(self) + + def error_message(self, message): + dialog = gtk.MessageDialog(None, + gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, + gtk.MESSAGE_ERROR, + gtk.BUTTONS_OK, + message) + dialog.run() + dialog.destroy() + + def on_window_destroy(self, widget, data = None): + gtk.main_quit() + + def main(self): + self.window.show() + gtk.main() + + def on_open_evolution_button_clicked(self, *args): + self.error_message('There is no saved evolution. You must create one first') + + def on_new_neural_network_button_clicked(self, *args): + self.new_neural_network_dialog.present() + + def on_new_neural_network_ok_button_clicked(self, *args): + nn_name = self.builder.get_object('new_nn_name').get_text() + ds_file_uri = self.builder.get_object('new_nn_dataset_file').get_filename() + + try: + neural_network.new(nn_name, self.store, ds_file_uri) + except Exception, err: + self.error_message(str(err)) + traceback.print_exc(file=sys.stdout) + else: + self.new_neural_network_dialog.hide() + + def on_new_evolution_button_clicked(self, *args): + self.new_evolution_dialog.present() + if __name__ == '__main__': - main() + app = evolution9_app() + app.main() diff --git a/src/util/music.py b/src/util/music.py index 352945b..a1b5b81 100644 --- a/src/util/music.py +++ b/src/util/music.py @@ -1,29 +1,34 @@ import random from mingus.containers.Note import Note from mingus.core import value note_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] dot_range = ['.', ''] class note(object): def __init__(self, note, octave, duration, dot): self.note = note - self.octave = octave + self.octave = '' if octave is None else octave self.duration = duration self.dot = dot + if self.note == 'P': + self.mingus_note = '0' + else: + self.mingus_note = Note(self.note, int(self.octave)) + def int_tuple(self): - return (int(Note(self.note + '-' + self.octave)), - value.dots(self.duration, int(bool(self.dot)))) + return (int(self.mingus_note), + value.dots(int(self.duration), int(bool(self.dot)))) def __str__(self): - return self.duration + self.note + self.octave + self.dot + return self.duration + self.note + self.dot + self.octave def random_note(): return note(random.choice(note_range), random.choice(octave_range), random.choice(duration_range), random.choice(dot_range)) diff --git a/src/util/rttl.py b/src/util/rttl.py index 98e1eb3..f425dd2 100644 --- a/src/util/rttl.py +++ b/src/util/rttl.py @@ -1,58 +1,63 @@ ''' Created on 12 Ara 2010 @author: melih ''' from util.music import note def parse(rttl_string): rttl_string = rttl_string.strip() track = [] parts = rttl_string.split(":") defaults = parts[1] notes = parts[2] if defaults: defaults = defaults.split(",") - defaultDuration = int(defaults[0].split("=")[1]) - defaultOctave = int(defaults[1].split("=")[1]) + defaultDuration = defaults[0].split("=")[1] + defaultOctave = defaults[1].split("=")[1] notes = notes.split(",") for n in notes: n = n.strip().upper() if defaults: duration = defaultDuration octave = defaultOctave - dot = 0 + dot = '' if n[0].isdigit(): if n[1].isdigit(): - duration = int(n[:2]) + duration = n[:2] n = n[2:] else: - duration = int(n[0]) + duration = n[0] n = n[1:] - if n.endswith("."): - dot = 1 - n = n[0:len(n) - 1] if n[len(n) - 1].isdigit(): - octave = int(n[len(n) - 1]) + octave = n[len(n) - 1] n = n[0:len(n) - 1] - - if n == "P": - n = None - + if n.endswith("."): + dot = '.' + n = n[0:len(n) - 1] + track.append(note(n, duration, octave, dot)) return track +def dataset_from_file(file_uri): + ds_file = file(file_uri) + ds_list = [] + + for line in ds_file: + track = parse(line) + ds_list.append(to_int(track)) + def dump(note_list): out = '::' for note in note_list: out += str(note) + ',' return out.rstrip(',') def to_int(note_list): return [x.int_tuple() for x in note_list] diff --git a/src/util/storage.py b/src/util/storage.py index 31dfcbb..3c87370 100644 --- a/src/util/storage.py +++ b/src/util/storage.py @@ -1,77 +1,164 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 +import pickle class db: - __connection__ = None + _connection = None def __init__(self): - self.connection = sqlite3.connect(SQLITE_FILE) - c = self.connection.cursor() + self._connection = sqlite3.connect(SQLITE_FILE) + c = self._connection.cursor() + + # Create neural networks table + c.execute(''' + CREATE TABLE IF NOT EXISTS neural_networks( + id INTEGER PRIMARY KEY, + name TEXT, + dataset TEXT, + trained BOOLEAN + ); + ''') - # Create table + # Create saved table c.execute(''' - create table if not exists composers( - generation integer, - parent integer, - gene text, - status text) - ''') + CREATE TABLE IF NOT EXISTS evolutions( + id INTEGER PRIMARY KEY, + name TEXT, + population_size INTEGER, + generation_count INTEGER, + evaluator INTEGER, + initialized BOOLEAN, + FOREIGN KEY(evaluator) REFERENCES neural_networks(id) + ); + ''') - self.commit() + # create genomes table + c.execute(''' + CREATE TABLE IF NOT EXISTS genomes( + id INTEGER PRIMARY KEY, + genome TEXT, + evolution_id INTEGER, + parent_1 INTEGER, + parent_2 INTEGER, + status TEXT, + FOREIGN KEY(evolution_id) REFERENCES evolutions(id) + ); + ''') + + self._commit() c.close() - def __commit__(self): - self.connection.commit() + def _commit(self): + self._connection.commit() - def __cursor__(self): - return self.connection.cursor() + @property + def _cursor(self): + return self._connection.cursor() - #Commits all transactions which aren't committed and closes db connection def close(self): - self.connection.close() - + self._connection.close() - #Inserts new song and returns its id - def put(self, generation, parent, genome, status): - c = self.cursor() + def save_evolution(self, name, population_size, evaluator, generation_count, initialized): + c = self._cursor + c.execute(''' - INSERT INTO composers VALUES (?,?,?,?) - ''', (generation,parent,gene,status)) + INSERT INTO evolutions (name, evaluator, population_size, generation_count, initialized) + VALUES(?, ?, ?, ?); + ''', (name, evaluator, population_size, generation_count, int(initialized))) + self._commit() - self.commit() c.execute(''' - SELECT ROWID FROM composers ORDER BY ROWID DESC LIMIT 1 - ''') + SELECT id FROM evolutions ORDER BY ROWID DESC LIMIT 1 + ''') rowid = c.fetchall() + c.close() return rowid[0][0] - - #Returns composer for the given row id - def get(self, rowid): - c = self.cursor() + + def update_evolution(self, row_id, generation_count, initialized): + c = self._cursor + + c.execute(''' + UPDATE evolutions SET generation_count=?, initialized=? WHERE id=?; + ''', (generation_count, int(initialized), row_id)) + + self._commit() + c.close() + + return + + #Returns evolution for the given row id + def get_evolution(self, rowid): + c = self._cursor() c.execute(''' - SELECT * FROM composers WHERE ROWID=? - ''',(rowid)) + SELECT * FROM evolutions WHERE id=? + ''', (rowid)) + result = c.fetchall() - return result[0] + c.close() + + return result[0] if result else None + + def get_evolution_list(self): + c = self._cursor() + c.execute(''' + SELECT * FROM evolutions + ''') + + result = c.fetchall() + c.close() + + return result + def new_neural_network(self, name, dataset): + c = self._cursor + + c.execute(''' + INSERT INTO neural_networks (name, dataset, trained) + VALUES(?, ?, ?); + ''', (name, pickle.dumps(dataset), 0)) + self._commit() + + c.close() + return + + def update_neural_network(self, row_id, trained): + c = self._cursor + + c.execute(''' + UPDATE neural_networks SET trained=? WHERE id=?; + ''', (int(trained), row_id)) + + self._commit() + c.close() + + return + + def get_neural_network_list(self): + c = self._cursor() + c.execute(''' + SELECT * FROM neural_networks + ''') + + result = c.fetchall() + c.close() + + return result + #Updates status of the given row id def update(self, rowid, status): c = self.cursor() c.execute(''' - UPDATE composers SET status=? WHERE ROWID=? - ''', (status, rowid)) + UPDATE composers SET status=? WHERE ROWID=? + ''', (status, rowid)) + self.commit() - - #prints all table with column names ROWID | GENERATION | PARENT | GENE | STATUS - def printAll(self): - c=self.cursor() - c.execute('SELECT ROWID,generation,parent,gene,status FROM COMPOSERS ORDER BY ROWID DESC') - for row in c: - print(row) + + c.close() + return
cagatay/Evolution-9
d42b47f7936a8375ee7cc9b3afbeba2c0806e5e1
latest
diff --git a/midi/Readfirst.txt b/midi/Readfirst.txt new file mode 100644 index 0000000..9ccbe18 --- /dev/null +++ b/midi/Readfirst.txt @@ -0,0 +1,21 @@ +ULTIMATE GM/GS Soundfont + +THIS ONLY WORKS WITH IF YOU HAVE EIGHT MEGS ON YOUR SB/32/64!!!!!! + +GM/GS Compatible Soundfont + +I got sick and tired of all the other junky GM/GS eight meg soundfonts so I made one with REALLY GOOD samples. And the Drumsets are actually unique from one another... Anyways I can't say much, you'll just have to listen. I spent about 6 months on this thing so the best thank you would be to hear your comments. So drop me a line. Also, Sorry for any inconvience geocities has caused... The keyword is "free". + +I'd also like to thank Uros Katic, he helped me a little on the way. Visit him at http://uts.ml.org/powergm/ He'll have a new site soon... He's working on "sonoro" For SB/live soundcards.. The Live is capable of allocating 32 megs max memory for soundfonts.. he's making the soundfont to sell on CD.. Check it out. + + + +You can do whatever u want with it, but just don't screw it up and sell or pass it out as yours. + + +Aug, 11, 98 (this is the FINAL version... I know what U are thinking) +To be used for non-commercial interests only. + +Copyrighted to me, Frank Wen 1998 + +Email: [email protected] [yes. exactly as it is.] diff --git a/midi/Ultimate.SF2 b/midi/Ultimate.SF2 new file mode 100644 index 0000000..040eb23 Binary files /dev/null and b/midi/Ultimate.SF2 differ diff --git a/midi/guitar.mid b/midi/guitar.mid new file mode 100644 index 0000000..0fc6af1 Binary files /dev/null and b/midi/guitar.mid differ diff --git a/src/NN.py b/src/brain/NN.py similarity index 100% rename from src/NN.py rename to src/brain/NN.py diff --git a/src/brain/__init__.py b/src/brain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/evolution/__init__.py b/src/evolution/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/evolution/genome.py b/src/evolution/genome.py new file mode 100644 index 0000000..bfc982c --- /dev/null +++ b/src/evolution/genome.py @@ -0,0 +1,13 @@ +from util import rttl + +class Song(object): + def __init__(self, genome): + if type(genome) == 'list': + self.note_list = genome + self.genome = rttl.dump(genome) + + elif type(genome) == 'string': + self.genome = genome + self.note_list = rttl.parse(genome) + + self.int_list = rttl.to_int(self.note_list) diff --git a/src/genome.py b/src/evolution/operators.py similarity index 86% rename from src/genome.py rename to src/evolution/operators.py index 85eee7c..4f75c2b 100644 --- a/src/genome.py +++ b/src/evolution/operators.py @@ -1,107 +1,98 @@ import random +from util import music GENOME_LENGTH = 20 -pitch_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] -duration_range = [str(2**x) for x in range(6)] -octave_range = [str(x) for x in range(4, 8)] -dot_range = ['.', ''] - ############################################################################## # Shortcuts ############################################################################## r = lambda x: random.randint(0, x) def r2(x): while(True): point_1 = r(x) point_2 = r(x) if point_1 != point_2: break if point_1 > point_2: point_1, point_2 = point_2, point_1 return point_1, point_2 ############################################################################## # Generators ############################################################################## def random_gene(): - pitch = random.choice(pitch_range) - duration = random.choice(duration_range) - octave = random.choice(octave_range) - dot = random.choice(dot_range) - - return (duration + pitch + octave + dot) + return music.random_note() def random_genome(): genome = [] for i in xrange(GENOME_LENGTH): genome.append(random_gene()) return genome ############################################################################## # Crossover operators ############################################################################## def one_point_crossover(father, mother): point = r(GENOME_LENGTH -1) child_1 = father[:point] + mother[point:] child_2 = mother[:point] + father[point:] return child_1, child_2 def two_point_crossover(father, mother): point_1, point_2 = r2(GENOME_LENGTH - 1) child_1 = father[:point_1] + mother[point_1:point_2] + father[point_2:] child_2 = mother[:point_1] + father[point_1:point_2] + mother[point_2:] return child_1, child_2 def uniform_crossover(father, mother): pool = father + mother random.shuffle(pool) return pool[:GENOME_LENGTH], pool[GENOME_LENGTH:] ############################################################################## # Mutation operators ############################################################################## def swap_mutation(genome): point_1, point_2 = r2(GENOME_LENGTH - 1) genome[point_1], genome[point_2] = genome[point_2], genome[point_1] def replace_mutation(genome): point = r(GENOME_LENGTH - 1) genome[point] = random_gene() def scramble_mutation(genome): point_1, point_2 = r2(GENOME_LENGTH - 1) temp = genome[point_1:point_2] random.shuffle(temp) genome[point_1:point_2] = temp def inversion_mutation(genome): point_1, point_2 = r2(GENOME_LENGTH - 1) temp = genome[point_1:point_2] temp.reverse() genome[point_1:point_2] = temp crossover_operators = [one_point_crossover, two_point_crossover, uniform_crossover] mutation_operators = [swap_mutation, replace_mutation, scramble_mutation, inversion_mutation] random_crossover = lambda x, y: random.choice(crossover_operators)(x, y) random_mutator = lambda x: random.choice(mutation_operators)(x) diff --git a/src/song.py b/src/song.py deleted file mode 100644 index f753cac..0000000 --- a/src/song.py +++ /dev/null @@ -1,22 +0,0 @@ -from mingus.containers.Track import Track -from mingus.core import value - -import util.RTTL - -class Song(Track): - def __init__(self, string): - super.__init__() - - song = RTTL.parse(string) - - for item in song.track: - self.add_notes(item.note, value.dots(item.duration, item.dot)) - - self._notes = list() - for bar in self: - for item in bar: - self.notes.append(int(item[2]), float(1/item[1])) - - @property - def notes(self): - return self._notes diff --git a/src/util/__init__.py b/src/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/util/music.py b/src/util/music.py new file mode 100644 index 0000000..352945b --- /dev/null +++ b/src/util/music.py @@ -0,0 +1,29 @@ +import random + +from mingus.containers.Note import Note +from mingus.core import value + +note_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] +duration_range = [str(2**x) for x in range(6)] +octave_range = [str(x) for x in range(4, 8)] +dot_range = ['.', ''] + +class note(object): + def __init__(self, note, octave, duration, dot): + self.note = note + self.octave = octave + self.duration = duration + self.dot = dot + + def int_tuple(self): + return (int(Note(self.note + '-' + self.octave)), + value.dots(self.duration, int(bool(self.dot)))) + + def __str__(self): + return self.duration + self.note + self.octave + self.dot + +def random_note(): + return note(random.choice(note_range), + random.choice(octave_range), + random.choice(duration_range), + random.choice(dot_range)) diff --git a/src/RTTL.py b/src/util/rttl.py similarity index 65% rename from src/RTTL.py rename to src/util/rttl.py index b4ba0d4..98e1eb3 100644 --- a/src/RTTL.py +++ b/src/util/rttl.py @@ -1,58 +1,58 @@ ''' Created on 12 Ara 2010 @author: melih ''' -def parse(rttl_string): - class song: - def __init__(self, name, track): - self.name = name - self.track = track - class note: - def __init__(self, duration, note, octave, dot): - self.duration = duration - self.note = note - if self.note: - self.note += '-' + str(octave) - self.dot = dot +from util.music import note +def parse(rttl_string): rttl_string = rttl_string.strip() - track = list() + track = [] parts = rttl_string.split(":") - name = parts[0] defaults = parts[1] notes = parts[2] if defaults: defaults = defaults.split(",") defaultDuration = int(defaults[0].split("=")[1]) defaultOctave = int(defaults[1].split("=")[1]) notes = notes.split(",") for n in notes: n = n.strip().upper() if defaults: duration = defaultDuration octave = defaultOctave dot = 0 if n[0].isdigit(): if n[1].isdigit(): duration = int(n[:2]) n = n[2:] else: duration = int(n[0]) n = n[1:] if n.endswith("."): dot = 1 n = n[0:len(n) - 1] if n[len(n) - 1].isdigit(): octave = int(n[len(n) - 1]) n = n[0:len(n) - 1] if n == "P": n = None - track.append(note(duration, n, octave, dot)) + track.append(note(n, duration, octave, dot)) - return song(name, track) + return track + +def dump(note_list): + out = '::' + + for note in note_list: + out += str(note) + ',' + + return out.rstrip(',') + +def to_int(note_list): + return [x.int_tuple() for x in note_list] diff --git a/src/storage.py b/src/util/storage.py similarity index 100% rename from src/storage.py rename to src/util/storage.py
cagatay/Evolution-9
39cb778c5719065e447ea2999ddc7f4b216bd4a4
latest
diff --git a/src/genome.py b/src/genome.py index 51be314..85eee7c 100644 --- a/src/genome.py +++ b/src/genome.py @@ -1,101 +1,107 @@ import random GENOME_LENGTH = 20 pitch_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] dot_range = ['.', ''] ############################################################################## # Shortcuts ############################################################################## r = lambda x: random.randint(0, x) def r2(x): while(True): point_1 = r(x) point_2 = r(x) if point_1 != point_2: break if point_1 > point_2: point_1, point_2 = point_2, point_1 return point_1, point_2 ############################################################################## -# generators +# Generators ############################################################################## def random_gene(): pitch = random.choice(pitch_range) duration = random.choice(duration_range) octave = random.choice(octave_range) dot = random.choice(dot_range) return (duration + pitch + octave + dot) def random_genome(): genome = [] for i in xrange(GENOME_LENGTH): genome.append(random_gene()) return genome ############################################################################## # Crossover operators ############################################################################## def one_point_crossover(father, mother): point = r(GENOME_LENGTH -1) child_1 = father[:point] + mother[point:] child_2 = mother[:point] + father[point:] return child_1, child_2 def two_point_crossover(father, mother): point_1, point_2 = r2(GENOME_LENGTH - 1) child_1 = father[:point_1] + mother[point_1:point_2] + father[point_2:] child_2 = mother[:point_1] + father[point_1:point_2] + mother[point_2:] return child_1, child_2 def uniform_crossover(father, mother): pool = father + mother random.shuffle(pool) return pool[:GENOME_LENGTH], pool[GENOME_LENGTH:] ############################################################################## # Mutation operators ############################################################################## def swap_mutation(genome): point_1, point_2 = r2(GENOME_LENGTH - 1) genome[point_1], genome[point_2] = genome[point_2], genome[point_1] def replace_mutation(genome): point = r(GENOME_LENGTH - 1) genome[point] = random_gene() def scramble_mutation(genome): point_1, point_2 = r2(GENOME_LENGTH - 1) temp = genome[point_1:point_2] random.shuffle(temp) genome[point_1:point_2] = temp def inversion_mutation(genome): point_1, point_2 = r2(GENOME_LENGTH - 1) temp = genome[point_1:point_2] temp.reverse() genome[point_1:point_2] = temp + +crossover_operators = [one_point_crossover, two_point_crossover, uniform_crossover] +mutation_operators = [swap_mutation, replace_mutation, scramble_mutation, inversion_mutation] + +random_crossover = lambda x, y: random.choice(crossover_operators)(x, y) +random_mutator = lambda x: random.choice(mutation_operators)(x)
cagatay/Evolution-9
040664720095cef57d297a08226ab773b02378c3
latest
diff --git a/src/genome.py b/src/genome.py index 3d255c1..51be314 100644 --- a/src/genome.py +++ b/src/genome.py @@ -1,101 +1,101 @@ import random GENOME_LENGTH = 20 pitch_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] duration_range = [str(2**x) for x in range(6)] octave_range = [str(x) for x in range(4, 8)] dot_range = ['.', ''] ############################################################################## # Shortcuts ############################################################################## r = lambda x: random.randint(0, x) +def r2(x): + while(True): + point_1 = r(x) + point_2 = r(x) + + if point_1 != point_2: + break + + if point_1 > point_2: + point_1, point_2 = point_2, point_1 + + return point_1, point_2 + +############################################################################## +# generators +############################################################################## + def random_gene(): pitch = random.choice(pitch_range) duration = random.choice(duration_range) octave = random.choice(octave_range) dot = random.choice(dot_range) return (duration + pitch + octave + dot) def random_genome(): genome = [] for i in xrange(GENOME_LENGTH): genome.append(random_gene()) return genome ############################################################################## # Crossover operators ############################################################################## def one_point_crossover(father, mother): point = r(GENOME_LENGTH -1) child_1 = father[:point] + mother[point:] child_2 = mother[:point] + father[point:] return child_1, child_2 def two_point_crossover(father, mother): - while(True): - point_1 = random.randint(0, GENOME_LENGTH - 1) - point_2 = random.randint(0, GENOME_LENGTH - 1) - if point_1 != point_2: - break + point_1, point_2 = r2(GENOME_LENGTH - 1) - if point_1 > point_2: - point_1, point_2 = point_2, point_1 - child_1 = father[:point_1] + mother[point_1:point_2] + father[point_2:] child_2 = mother[:point_1] + father[point_1:point_2] + mother[point_2:] return child_1, child_2 def uniform_crossover(father, mother): pool = father + mother random.shuffle(pool) return pool[:GENOME_LENGTH], pool[GENOME_LENGTH:] ############################################################################## # Mutation operators ############################################################################## def swap_mutation(genome): - point_1 = random.randint(0, GENOME_LENGTH - 1) - point_2 = random.randint(0, GENOME_LENGTH - 1) + point_1, point_2 = r2(GENOME_LENGTH - 1) genome[point_1], genome[point_2] = genome[point_2], genome[point_1] def replace_mutation(genome): - point = random.randint(0, GENOME_LENGTH -1) + point = r(GENOME_LENGTH - 1) genome[point] = random_gene() def scramble_mutation(genome): - point_1 = random.randint(0, GENOME_LENGTH -1) - point_2 = random.randint(0, GENOME_LENGTH -1) - - if point_1 > point_2: - point_2, point_1 = point_1, point_2 + point_1, point_2 = r2(GENOME_LENGTH - 1) temp = genome[point_1:point_2] random.shuffle(temp) genome[point_1:point_2] = temp def inversion_mutation(genome): - point_1 = random.randint(0, GENOME_LENGTH -1) - point_2 = random.randint(0, GENOME_LENGTH -1) - - if point_1 > point_2: - point_2, point_1 = point_1, point_2 + point_1, point_2 = r2(GENOME_LENGTH - 1) temp = genome[point_1:point_2] temp.reverse() genome[point_1:point_2] = temp -
cagatay/Evolution-9
633b7ddfcaa81ebcef6e24647dd1d0fcd0380d18
latest
diff --git a/.gitignore b/.gitignore index a6d48fe..49ff695 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ output/* *.pyc +*.swp diff --git a/src/brain/NN.py b/src/NN.py similarity index 95% rename from src/brain/NN.py rename to src/NN.py index 30b2668..df817cc 100644 --- a/src/brain/NN.py +++ b/src/NN.py @@ -1,144 +1,144 @@ from pybrain.tools.shortcuts import buildNetwork -from mingus.containers import * +from mingus.containers.Note import Note from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import constants import pickle import math class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 hiddenLayerNodeCount = 20 durationPerNote = 2; ds = SupervisedDataSet(inputCount, outputCount) def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount self.durationPerNote = _durationPerNote self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) def train(self): trainer = BackpropTrainer(self.net, self.ds, verbose=True) trainer.trainUntilConvergence() # for i in range(0,5000): # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) # trainer.trainEpochs(1) # print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) # def addSong(self, song): song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): #sampleOutputList.append( song.intList[ z ] ) sampleOutputList.append( 1 ) self.ds.addSample( sampleList, sampleOutputList ) sampleList = list() sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 return song def fitness(self, song): returnValue = 0.0 song = self.attachIntList( song ) i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 - return returnValue \ No newline at end of file + return returnValue diff --git a/src/RTTL.py b/src/RTTL.py new file mode 100644 index 0000000..b4ba0d4 --- /dev/null +++ b/src/RTTL.py @@ -0,0 +1,58 @@ +''' +Created on 12 Ara 2010 + +@author: melih +''' + +def parse(rttl_string): + class song: + def __init__(self, name, track): + self.name = name + self.track = track + class note: + def __init__(self, duration, note, octave, dot): + self.duration = duration + self.note = note + if self.note: + self.note += '-' + str(octave) + self.dot = dot + + rttl_string = rttl_string.strip() + track = list() + parts = rttl_string.split(":") + name = parts[0] + defaults = parts[1] + notes = parts[2] + + if defaults: + defaults = defaults.split(",") + defaultDuration = int(defaults[0].split("=")[1]) + defaultOctave = int(defaults[1].split("=")[1]) + + notes = notes.split(",") + for n in notes: + n = n.strip().upper() + if defaults: + duration = defaultDuration + octave = defaultOctave + dot = 0 + if n[0].isdigit(): + if n[1].isdigit(): + duration = int(n[:2]) + n = n[2:] + else: + duration = int(n[0]) + n = n[1:] + if n.endswith("."): + dot = 1 + n = n[0:len(n) - 1] + if n[len(n) - 1].isdigit(): + octave = int(n[len(n) - 1]) + n = n[0:len(n) - 1] + + if n == "P": + n = None + + track.append(note(duration, n, octave, dot)) + + return song(name, track) diff --git a/src/brain/__init__.py b/src/brain/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/db/__init__.py b/src/db/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/evolution/__init__.py b/src/evolution/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/evolve.py b/src/evolve.py index b3b1c8a..fb014b2 100755 --- a/src/evolve.py +++ b/src/evolve.py @@ -1,71 +1,31 @@ #!/usr/bin/env python ''' Created on Oct 6, 2010 @author: cagatay ''' -from random import randrange -from random import random - -from evolution9.midi.midiActions import createMIDI -from evolution9.evolution.storage import db from pybrain.tools.shortcuts import buildNetwork from mingus.midi.MidiFileIn import MIDI_to_Composition from mingus.midi.MidiFileOut import write_Track from mingus.containers import * from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import mingus.core.notes as notes -import mingus.core.value as value -import RTTL import os import constants -from NN import NN +from brain import NN +def main(): + while(True): + pass if __name__ == '__main__': - - ''' - currentNN = NN("yeni",3,1) - - for song in songList: - currentNN.addSong( song ) - - currentNN.train() - - currentNN.saveNetworkToFile() - - #currentNN.readNetworkFromFile() - - songList = RTTL.parse(constants.INPUT_DIR + "metallica.txt") - - sonuc = currentNN.fitness( songList[0] ) - - print sonuc - - sonuc = currentNN.fitness( songList[1] ) - - print sonuc - - songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") - - sonuc = currentNN.fitness( songList[6] ) - - print sonuc - - ''' - songs = RTTL.parse(constants.INPUT_DIR + "beatles.txt") for song in songs: track = Track() for n in song.track: track.add_notes(n.note, value.dots(n.duration, n.dot)) write_Track(constants.OUTPUT_DIR + song.name + ".mid", track, song.tempo) - -# storage = db.Database() -# storage.initDatabase() -# storage.printAll() -# composition = list() diff --git a/src/genome.py b/src/genome.py new file mode 100644 index 0000000..3d255c1 --- /dev/null +++ b/src/genome.py @@ -0,0 +1,101 @@ +import random + +GENOME_LENGTH = 20 + +pitch_range = ['P', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] +duration_range = [str(2**x) for x in range(6)] +octave_range = [str(x) for x in range(4, 8)] +dot_range = ['.', ''] + +############################################################################## +# Shortcuts +############################################################################## + +r = lambda x: random.randint(0, x) + +def random_gene(): + pitch = random.choice(pitch_range) + duration = random.choice(duration_range) + octave = random.choice(octave_range) + dot = random.choice(dot_range) + + return (duration + pitch + octave + dot) + +def random_genome(): + genome = [] + + for i in xrange(GENOME_LENGTH): + genome.append(random_gene()) + + return genome + +############################################################################## +# Crossover operators +############################################################################## + +def one_point_crossover(father, mother): + point = r(GENOME_LENGTH -1) + + child_1 = father[:point] + mother[point:] + child_2 = mother[:point] + father[point:] + + return child_1, child_2 + +def two_point_crossover(father, mother): + while(True): + point_1 = random.randint(0, GENOME_LENGTH - 1) + point_2 = random.randint(0, GENOME_LENGTH - 1) + if point_1 != point_2: + break + + if point_1 > point_2: + point_1, point_2 = point_2, point_1 + + child_1 = father[:point_1] + mother[point_1:point_2] + father[point_2:] + child_2 = mother[:point_1] + father[point_1:point_2] + mother[point_2:] + + return child_1, child_2 + +def uniform_crossover(father, mother): + pool = father + mother + random.shuffle(pool) + + return pool[:GENOME_LENGTH], pool[GENOME_LENGTH:] + +############################################################################## +# Mutation operators +############################################################################## + +def swap_mutation(genome): + point_1 = random.randint(0, GENOME_LENGTH - 1) + point_2 = random.randint(0, GENOME_LENGTH - 1) + + genome[point_1], genome[point_2] = genome[point_2], genome[point_1] + +def replace_mutation(genome): + point = random.randint(0, GENOME_LENGTH -1) + genome[point] = random_gene() + +def scramble_mutation(genome): + point_1 = random.randint(0, GENOME_LENGTH -1) + point_2 = random.randint(0, GENOME_LENGTH -1) + + if point_1 > point_2: + point_2, point_1 = point_1, point_2 + + temp = genome[point_1:point_2] + random.shuffle(temp) + + genome[point_1:point_2] = temp + +def inversion_mutation(genome): + point_1 = random.randint(0, GENOME_LENGTH -1) + point_2 = random.randint(0, GENOME_LENGTH -1) + + if point_1 > point_2: + point_2, point_1 = point_1, point_2 + + temp = genome[point_1:point_2] + temp.reverse() + genome[point_1:point_2] = temp + diff --git a/src/main.py b/src/main.py new file mode 100755 index 0000000..906c49e --- /dev/null +++ b/src/main.py @@ -0,0 +1,12 @@ +#!/usr/bin/python2.6 +import gtk + +def main(): + builder = gtk.Builder() + builder.add_from_file('res/gui.glade') + window = builder.get_object('window') + window.show() + gtk.main() + +if __name__ == '__main__': + main() diff --git a/src/res/gui.glade b/src/res/gui.glade new file mode 100644 index 0000000..448fc21 --- /dev/null +++ b/src/res/gui.glade @@ -0,0 +1,178 @@ +<?xml version="1.0" encoding="UTF-8"?> +<interface> + <requires lib="gtk+" version="2.24"/> + <!-- interface-naming-policy project-wide --> + <object class="GtkListStore" id="liststore1"/> + <object class="GtkWindow" id="window1"> + <property name="can_focus">False</property> + <property name="title" translatable="yes">Evolution 9</property> + <property name="default_width">600</property> + <property name="default_height">400</property> + <signal name="destroy" handler="gtk_main_quit" swapped="no"/> + <child> + <object class="GtkVBox" id="vbox1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkToolbar" id="toolbar1"> + <property name="height_request">40</property> + <property name="visible">True</property> + <property name="can_focus">False</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkHBox" id="hbox1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkVBox" id="vbox3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkHButtonBox" id="hbuttonbox1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkButton" id="button1"> + <property name="label" translatable="yes">Play</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_action_appearance">False</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="button2"> + <property name="label" translatable="yes">FastForward</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_action_appearance">False</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">False</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkScrolledWindow" id="scrolledwindow1"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hscrollbar_policy">automatic</property> + <property name="vscrollbar_policy">automatic</property> + <child> + <object class="GtkTreeView" id="treeview2"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="model">liststore1</property> + </object> + </child> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkVBox" id="vbox4"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <placeholder/> + </child> + <child> + <object class="GtkNotebook" id="notebook1"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <child> + <placeholder/> + </child> + <child type="tab"> + <object class="GtkLabel" id="label1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes">page 1</property> + </object> + <packing> + <property name="tab_fill">False</property> + </packing> + </child> + <child> + <placeholder/> + </child> + <child type="tab"> + <object class="GtkLabel" id="label2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes">page 2</property> + </object> + <packing> + <property name="position">1</property> + <property name="tab_fill">False</property> + </packing> + </child> + <child> + <placeholder/> + </child> + <child type="tab"> + <object class="GtkLabel" id="label3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes">page 3</property> + </object> + <packing> + <property name="position">2</property> + <property name="tab_fill">False</property> + </packing> + </child> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + </object> +</interface> diff --git a/src/song.py b/src/song.py new file mode 100644 index 0000000..f753cac --- /dev/null +++ b/src/song.py @@ -0,0 +1,22 @@ +from mingus.containers.Track import Track +from mingus.core import value + +import util.RTTL + +class Song(Track): + def __init__(self, string): + super.__init__() + + song = RTTL.parse(string) + + for item in song.track: + self.add_notes(item.note, value.dots(item.duration, item.dot)) + + self._notes = list() + for bar in self: + for item in bar: + self.notes.append(int(item[2]), float(1/item[1])) + + @property + def notes(self): + return self._notes diff --git a/src/db/db.py b/src/storage.py similarity index 61% rename from src/db/db.py rename to src/storage.py index 135d09b..31dfcbb 100644 --- a/src/db/db.py +++ b/src/storage.py @@ -1,84 +1,77 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' from constants import SQLITE_FILE import sqlite3 -class Database: +class db: __connection__ = None - def initDatabase(self): + def __init__(self): self.connection = sqlite3.connect(SQLITE_FILE) c = self.connection.cursor() + # Create table c.execute(''' create table if not exists composers( generation integer, parent integer, gene text, status text) ''') + + self.commit() c.close() - #Commits all transactions which aren't committed and closes db connection - def closeDatabase(self): + def __commit__(self): self.connection.commit() + + def __cursor__(self): + return self.connection.cursor() + + #Commits all transactions which aren't committed and closes db connection + def close(self): self.connection.close() - #Inserts new composer and returns its id - def newComposer(self,generation,parent,gene,status): - c=self.connection.cursor() - t =(generation,parent,gene,status) + #Inserts new song and returns its id + def put(self, generation, parent, genome, status): + c = self.cursor() c.execute(''' INSERT INTO composers VALUES (?,?,?,?) - ''',t) - self.connection.commit() + ''', (generation,parent,gene,status)) + + self.commit() c.execute(''' SELECT ROWID FROM composers ORDER BY ROWID DESC LIMIT 1 ''') - insertedRowId = c.fetchall() + rowid = c.fetchall() c.close() - return insertedRowId[0][0] - + return rowid[0][0] #Returns composer for the given row id - def getComposer(self,rowId): - t = (rowId,) - c=self.connection.cursor() + def get(self, rowid): + c = self.cursor() c.execute(''' SELECT * FROM composers WHERE ROWID=? - ''',t) - result=c.fetchall() + ''',(rowid)) + result = c.fetchall() return result[0] #Updates status of the given row id - def updateStatus(self,rowId,newStatus): - t = (newStatus,rowId,) - c=self.connection.cursor() + def update(self, rowid, status): + c = self.cursor() c.execute(''' UPDATE composers SET status=? WHERE ROWID=? - ''',t) - self.connection.commit() + ''', (status, rowid)) + self.commit() #prints all table with column names ROWID | GENERATION | PARENT | GENE | STATUS def printAll(self): - c=self.connection.cursor() + c=self.cursor() c.execute('SELECT ROWID,generation,parent,gene,status FROM COMPOSERS ORDER BY ROWID DESC') for row in c: print(row) - - - - - - - - - - - - diff --git a/src/train.py b/src/train.py index e69de29..bcefab7 100755 --- a/src/train.py +++ b/src/train.py @@ -0,0 +1,24 @@ +from util.song import Song + +def read_input(filename): + songs = list() + + input_file = file(filename) + for line in input_file: + songs.append(Song(line)) + + return songs + +def main(): + currentNN = NN("yeni",3,1) + + songs = read_input('beatles.txt') + + for song in songs: + currentNN.addSong(song) + currentNN.train() + + currentNN.saveNetworkToFile() + +if __name__ == '__main__': + main() diff --git a/src/util/RTTL.py b/src/util/RTTL.py deleted file mode 100644 index 76e9ca5..0000000 --- a/src/util/RTTL.py +++ /dev/null @@ -1,67 +0,0 @@ -''' -Created on 12 Ara 2010 - -@author: melih -''' - -def parse(fileName): - file = open(fileName) - songs = list() - - - for line in file: - line = line.rstrip() - track = list() - parts = line.split(":") - name = parts[0] - defaults = parts[1] - notes = parts[2] - - - defaults = defaults.split(",") - defaultDuration = int(defaults[0].split("=")[1]) - defaultOctave = int(defaults[1].split("=")[1]) - tempo = int(defaults[2].split("=")[1]) - - - notes = notes.split(",") - for n in notes: - n = n.upper() - duration = defaultDuration - octave = defaultOctave - dot = 0 - if n[0].isdigit(): - if n[1].isdigit(): - duration = int(n[:2]) - n = n[2:] - else: - duration = int(n[0]) - n = n[1:] - if n[len(n) - 1].isdigit(): - octave = int(n[len(n) - 1]) - n = n[0:len(n) - 1] - - if n.endswith("."): - dot = 1 - n = n[0:len(n) - 1] - if n == "P": - n = None - - track.append(note(duration, n, octave, dot)) - - songs.append(song(name, track, tempo)) - - return songs - -class song: - def __init__(self, name, track, tempo): - self.name = name - self.track = track - self.tempo = tempo -class note: - def __init__(self, duration, note, octave, dot): - self.duration = duration - self.note = note - if self.note: - self.note += '-' + str(octave) - self.dot = dot diff --git a/src/util/__init__.py b/src/util/__init__.py deleted file mode 100644 index e69de29..0000000
cagatay/Evolution-9
e01140e44a8240d10f9e95a3f44605682abb2ade
latest
diff --git a/.gitignore b/.gitignore index 5fca3f8..a6d48fe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -/output +output/* *.pyc
cagatay/Evolution-9
901a9c2536f15d216b6ed531c4526b0823ee1211
RTTL parser is updated, code organization
diff --git a/.gitignore b/.gitignore index 1f57b97..5fca3f8 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /output +*.pyc diff --git a/.pydevproject b/.pydevproject index 8076667..d3ed789 100644 --- a/.pydevproject +++ b/.pydevproject @@ -1,10 +1,10 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<?eclipse-pydev version="1.0"?> - -<pydev_project> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python26</pydev_property> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.6</pydev_property> -<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> -<path>/Evolution-9/src</path> -</pydev_pathproperty> -</pydev_project> +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?eclipse-pydev version="1.0"?> + +<pydev_project> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.6</pydev_property> +<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> +<path>/Evolution-9/src</path> +</pydev_pathproperty> +</pydev_project> diff --git a/save/yeni-3-3 b/save/yeni-3-3 new file mode 100644 index 0000000..88e371e --- /dev/null +++ b/save/yeni-3-3 @@ -0,0 +1,927 @@ +ccopy_reg +_reconstructor +p0 +(cpybrain.structure.networks.feedforward +FeedForwardNetwork +p1 +c__builtin__ +object +p2 +Ntp3 +Rp4 +(dp5 +S'indim' +p6 +I3 +sS'modulesSorted' +p7 +(lp8 +g0 +(cpybrain.structure.modules.biasunit +BiasUnit +p9 +g2 +Ntp10 +Rp11 +(dp12 +g6 +I0 +sS'inputbuffer' +p13 +cnumpy.core.multiarray +_reconstruct +p14 +(cnumpy +ndarray +p15 +(I0 +tp16 +S'b' +p17 +tp18 +Rp19 +(I1 +(I1 +I0 +tp20 +cnumpy +dtype +p21 +(S'f8' +p22 +I0 +I1 +tp23 +Rp24 +(I3 +S'<' +p25 +NNNI-1 +I-1 +I0 +tp26 +bI00 +S'' +p27 +tp28 +bsS'outputerror' +p29 +g14 +(g15 +(I0 +tp30 +g17 +tp31 +Rp32 +(I1 +(I1 +I1 +tp33 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00' +p34 +tp35 +bsS'inputerror' +p36 +g14 +(g15 +(I0 +tp37 +g17 +tp38 +Rp39 +(I1 +(I1 +I0 +tp40 +g24 +I00 +g27 +tp41 +bsS'outputbuffer' +p42 +g14 +(g15 +(I0 +tp43 +g17 +tp44 +Rp45 +(I1 +(I1 +I1 +tp46 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\xf0?' +p47 +tp48 +bsS'_name' +p49 +S'bias' +p50 +sS'argdict' +p51 +(dp52 +S'name' +p53 +g50 +ssS'outdim' +p54 +I1 +sS'offset' +p55 +I0 +sS'bufferlist' +p56 +(lp57 +(g13 +I0 +tp58 +a(g36 +I0 +tp59 +a(g42 +I1 +tp60 +a(g29 +I1 +tp61 +asbag0 +(cpybrain.structure.modules.linearlayer +LinearLayer +p62 +g2 +Ntp63 +Rp64 +(dp65 +g6 +I3 +sg13 +g14 +(g15 +(I0 +tp66 +g17 +tp67 +Rp68 +(I1 +(I1 +I3 +tp69 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00P@\x00\x00\x00\x00\x00\x00P@\x00\x00\x00\x00\x00\x00P@' +p70 +tp71 +bsS'dim' +p72 +I3 +sg29 +g14 +(g15 +(I0 +tp73 +g17 +tp74 +Rp75 +(I1 +(I1 +I3 +tp76 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p77 +tp78 +bsg36 +g14 +(g15 +(I0 +tp79 +g17 +tp80 +Rp81 +(I1 +(I1 +I3 +tp82 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p83 +tp84 +bsg42 +g14 +(g15 +(I0 +tp85 +g17 +tp86 +Rp87 +(I1 +(I1 +I3 +tp88 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00P@\x00\x00\x00\x00\x00\x00P@\x00\x00\x00\x00\x00\x00P@' +p89 +tp90 +bsg49 +S'in' +p91 +sg51 +(dp92 +g72 +I3 +sg53 +g91 +ssg54 +I3 +sg55 +I0 +sg56 +(lp93 +(g13 +I3 +tp94 +a(g36 +I3 +tp95 +a(g42 +I3 +tp96 +a(g29 +I3 +tp97 +asbag0 +(cpybrain.structure.modules.sigmoidlayer +SigmoidLayer +p98 +g2 +Ntp99 +Rp100 +(dp101 +g6 +I6 +sg13 +g14 +(g15 +(I0 +tp102 +g17 +tp103 +Rp104 +(I1 +(I1 +I6 +tp105 +g24 +I00 +S'\xb2\xa3\xb0\xde\xb9$b@\xe4\x99%:\xf6,t@\xf3K\x97D5\x106\xc0\xe3\x90\xbbE\xa8\xd1p@\x96\xf2)\xaaU`\xb7@\xfd\x99\xbf\xfb\xa6\x19`\xc0' +p106 +tp107 +bsg72 +I6 +sg29 +g14 +(g15 +(I0 +tp108 +g17 +tp109 +Rp110 +(I1 +(I1 +I6 +tp111 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p112 +tp113 +bsg36 +g14 +(g15 +(I0 +tp114 +g17 +tp115 +Rp116 +(I1 +(I1 +I6 +tp117 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p118 +tp119 +bsg42 +g14 +(g15 +(I0 +tp120 +g17 +tp121 +Rp122 +(I1 +(I1 +I6 +tp123 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?O\xfb\xa1\xab8\xfe\xf1=\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x906\xa4O\x8a\x1bR4' +p124 +tp125 +bsg49 +S'hidden0' +p126 +sg51 +(dp127 +g72 +I6 +sg53 +g126 +ssg54 +I6 +sg55 +I0 +sg56 +(lp128 +(g13 +I6 +tp129 +a(g36 +I6 +tp130 +a(g42 +I6 +tp131 +a(g29 +I6 +tp132 +asbag0 +(g62 +g2 +Ntp133 +Rp134 +(dp135 +g6 +I3 +sg13 +g14 +(g15 +(I0 +tp136 +g17 +tp137 +Rp138 +(I1 +(I1 +I3 +tp139 +g24 +I00 +S")\xb4\x9b\x80\xcc\x13M@\xe2\x1b'M\xc6\xefI@\x08\x11\x19:+\xcbI@" +p140 +tp141 +bsg72 +I3 +sg29 +g14 +(g15 +(I0 +tp142 +g17 +tp143 +Rp144 +(I1 +(I1 +I3 +tp145 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p146 +tp147 +bsg36 +g14 +(g15 +(I0 +tp148 +g17 +tp149 +Rp150 +(I1 +(I1 +I3 +tp151 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p152 +tp153 +bsg42 +g14 +(g15 +(I0 +tp154 +g17 +tp155 +Rp156 +(I1 +(I1 +I3 +tp157 +g24 +I00 +S")\xb4\x9b\x80\xcc\x13M@\xe2\x1b'M\xc6\xefI@\x08\x11\x19:+\xcbI@" +p158 +tp159 +bsg49 +S'out' +p160 +sg51 +(dp161 +g72 +I3 +sg53 +g160 +ssg54 +I3 +sg55 +I0 +sg56 +(lp162 +(g13 +I3 +tp163 +a(g36 +I3 +tp164 +a(g42 +I3 +tp165 +a(g29 +I3 +tp166 +asbasS'inmodules' +p167 +(lp168 +g64 +asg29 +g14 +(g15 +(I0 +tp169 +g17 +tp170 +Rp171 +(I1 +(I1 +I3 +tp172 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p173 +tp174 +bsg36 +g14 +(g15 +(I0 +tp175 +g17 +tp176 +Rp177 +(I1 +(I1 +I3 +tp178 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p179 +tp180 +bsS'_derivs' +p181 +g14 +(g15 +(I0 +tp182 +g17 +tp183 +Rp184 +(I1 +(I45 +tp185 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p186 +tp187 +bsS'modules' +p188 +c__builtin__ +set +p189 +((lp190 +g64 +ag134 +ag11 +ag100 +atp191 +Rp192 +sg42 +g14 +(g15 +(I0 +tp193 +g17 +tp194 +Rp195 +(I1 +(I1 +I3 +tp196 +g24 +I00 +S")\xb4\x9b\x80\xcc\x13M@\xe2\x1b'M\xc6\xefI@\x08\x11\x19:+\xcbI@" +p197 +tp198 +bsg49 +S'FeedForwardNetwork-17' +p199 +sS'connections' +p200 +(dp201 +g64 +(lp202 +g0 +(cpybrain.structure.connections.full +FullConnection +p203 +g2 +Ntp204 +Rp205 +(dp206 +g6 +I3 +sg54 +I6 +sS'outSliceFrom' +p207 +I0 +sS'inSliceTo' +p208 +I3 +sS'inmod' +p209 +g64 +sg181 +g14 +(g15 +(I0 +tp210 +g17 +tp211 +Rp212 +(I1 +(I18 +tp213 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p214 +tp215 +bsS'outmod' +p216 +g100 +sg49 +S'FullConnection-13' +p217 +sg51 +(dp218 +g209 +g64 +sg216 +g100 +ssS'paramdim' +p219 +I18 +sS'owner' +p220 +g4 +sS'outSliceTo' +p221 +I6 +sS'hasDerivatives' +p222 +I01 +sS'inSliceFrom' +p223 +I0 +sS'_params' +p224 +g14 +(g15 +(I0 +tp225 +g17 +tp226 +Rp227 +(I1 +(I18 +tp228 +g24 +I00 +S'\xfc\xba2\xa6\xe6\x10\xf2?\x0e\xd8?|xa\xb9\xbf\x89A\x89\xf1\xb3\x06\xf3?\x98o\xb6?\x8cN\xf4?\xbb\xb8\xac\x80\x9c\xf0\xf3?\x89\x15\x90\x02l+\x04@v\xce\nL\x13\x02\xe0?X\xbd\xed\x07\xa4\x9c\xdb?R\xce\xc7\xa4\xdd\x0c\xf5\xbf1\xfbZ\x04d;\x00@a\xc6\xd6\xed\xb2\x12\xbf?\x0cP\xd8\xa2\x14;\x00@\xd5\xde\xbe\xea\xf1;W@\xfc)\xca<\x00o\xba?~\xd8\xdb(\xf0:\xdb?6uH\xe6V\xb0\xde\xbf\xa2\xeeW\xf4\x1e<\xfc\xbf\xabj\x1f\xac]\x13\xd0?' +p229 +tp230 +bsbasg134 +(lp231 +sg11 +(lp232 +g0 +(g203 +g2 +Ntp233 +Rp234 +(dp235 +g6 +I1 +sg54 +I3 +sg207 +I0 +sg208 +I1 +sg209 +g11 +sg181 +g14 +(g15 +(I0 +tp236 +g17 +tp237 +Rp238 +(I1 +(I3 +tp239 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p240 +tp241 +bsg216 +g134 +sg49 +S'FullConnection-14' +p242 +sg51 +(dp243 +g209 +g11 +sg216 +g134 +ssg219 +I3 +sg220 +g4 +sg221 +I3 +sg222 +I01 +sg223 +I0 +sg224 +g14 +(g15 +(I0 +tp244 +g17 +tp245 +Rp246 +(I1 +(I3 +tp247 +g24 +I00 +S"\x14\x88m\xe8\xe7y'@j\x8be<\xc8\x9b'@\x9e\xcb\xae\xf0\x9f\xb4&@" +p248 +tp249 +bsbag0 +(g203 +g2 +Ntp250 +Rp251 +(dp252 +g6 +I1 +sg54 +I6 +sg207 +I0 +sg208 +I1 +sg209 +g11 +sg181 +g14 +(g15 +(I0 +tp253 +g17 +tp254 +Rp255 +(I1 +(I6 +tp256 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p257 +tp258 +bsg216 +g100 +sg49 +S'FullConnection-15' +p259 +sg51 +(dp260 +g209 +g11 +sg216 +g100 +ssg219 +I6 +sg220 +g4 +sg221 +I6 +sg222 +I01 +sg223 +I0 +sg224 +g14 +(g15 +(I0 +tp261 +g17 +tp262 +Rp263 +(I1 +(I6 +tp264 +g24 +I00 +S"\xe4\x0b)\xad\x15\xfe\x08@\x9e'\x14\x13#\xd8\xdd?\x89\x98$t\xb5\x13\x04@\x0b+\x90j&!\xfa?\x87\xf7*\x98yh\x04@f\xad@'-\xfc\xf3\xbf" +p265 +tp266 +bsbasg100 +(lp267 +g0 +(g203 +g2 +Ntp268 +Rp269 +(dp270 +g6 +I6 +sg54 +I3 +sg207 +I0 +sg208 +I6 +sg209 +g100 +sg181 +g14 +(g15 +(I0 +tp271 +g17 +tp272 +Rp273 +(I1 +(I18 +tp274 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' +p275 +tp276 +bsg216 +g134 +sg49 +S'FullConnection-16' +p277 +sg51 +(dp278 +g209 +g100 +sg216 +g134 +ssg219 +I18 +sg220 +g4 +sg221 +I3 +sg222 +I01 +sg223 +I0 +sg224 +g14 +(g15 +(I0 +tp279 +g17 +tp280 +Rp281 +(I1 +(I18 +tp282 +g24 +I00 +S'\x877,\xf7p?*@\xd6\xa2H\x9eI\xde$@\x08)\x0c\xf5\xcd\x840\xc0E\xf5\x86\x07\x97\xa9#@\x12\xa0*}\xf8\r*@y\xd6\xdeL\xb5\xa9\x14@\xc2r\x93\xd5\xfb8)@`.#\xb6\xacP @\xe0\xafj?eL\xfa?z2O\xcc\xe24"@"^-\xa0\xc5d$@\x99\xd6\x0b\\\x83e\x10\xc0l5lD\xd8\x87"@0}\xb5\xc13\x9e&@]\rQm\x1b\xb2\x03\xc0\x1a\xfc\x93\xa7\x1e\xf6\'@\xba\xa6\n\x94\xc4\xb7\x1e@x\xdf\xe1\xea\xd9\xb2\x11\xc0' +p283 +tp284 +bsbassS'motherconnections' +p285 +(lp286 +sg13 +g14 +(g15 +(I0 +tp287 +g17 +tp288 +Rp289 +(I1 +(I1 +I3 +tp290 +g24 +I00 +S'\x00\x00\x00\x00\x00\x00P@\x00\x00\x00\x00\x00\x00P@\x00\x00\x00\x00\x00\x00P@' +p291 +tp292 +bsg51 +(dp293 +g53 +g199 +ssg54 +I3 +sS'outmodules' +p294 +(lp295 +g134 +asg219 +I45 +sg56 +(lp296 +(g13 +I3 +tp297 +a(g36 +I3 +tp298 +a(g42 +I3 +tp299 +a(g29 +I3 +tp300 +asS'sorted' +p301 +I01 +sS'_Network__offset' +p302 +I0 +sg222 +I01 +sg224 +g14 +(g15 +(I0 +tp303 +g17 +tp304 +Rp305 +(I1 +(I45 +tp306 +g24 +I00 +S'\x14\x88m\xe8\xe7y\'@j\x8be<\xc8\x9b\'@\x9e\xcb\xae\xf0\x9f\xb4&@\xe4\x0b)\xad\x15\xfe\x08@\x9e\'\x14\x13#\xd8\xdd?\x89\x98$t\xb5\x13\x04@\x0b+\x90j&!\xfa?\x87\xf7*\x98yh\x04@f\xad@\'-\xfc\xf3\xbf\xfc\xba2\xa6\xe6\x10\xf2?\x0e\xd8?|xa\xb9\xbf\x89A\x89\xf1\xb3\x06\xf3?\x98o\xb6?\x8cN\xf4?\xbb\xb8\xac\x80\x9c\xf0\xf3?\x89\x15\x90\x02l+\x04@v\xce\nL\x13\x02\xe0?X\xbd\xed\x07\xa4\x9c\xdb?R\xce\xc7\xa4\xdd\x0c\xf5\xbf1\xfbZ\x04d;\x00@a\xc6\xd6\xed\xb2\x12\xbf?\x0cP\xd8\xa2\x14;\x00@\xd5\xde\xbe\xea\xf1;W@\xfc)\xca<\x00o\xba?~\xd8\xdb(\xf0:\xdb?6uH\xe6V\xb0\xde\xbf\xa2\xeeW\xf4\x1e<\xfc\xbf\xabj\x1f\xac]\x13\xd0?\x877,\xf7p?*@\xd6\xa2H\x9eI\xde$@\x08)\x0c\xf5\xcd\x840\xc0E\xf5\x86\x07\x97\xa9#@\x12\xa0*}\xf8\r*@y\xd6\xdeL\xb5\xa9\x14@\xc2r\x93\xd5\xfb8)@`.#\xb6\xacP @\xe0\xafj?eL\xfa?z2O\xcc\xe24"@"^-\xa0\xc5d$@\x99\xd6\x0b\\\x83e\x10\xc0l5lD\xd8\x87"@0}\xb5\xc13\x9e&@]\rQm\x1b\xb2\x03\xc0\x1a\xfc\x93\xa7\x1e\xf6\'@\xba\xa6\n\x94\xc4\xb7\x1e@x\xdf\xe1\xea\xd9\xb2\x11\xc0' +p307 +tp308 +bsb. \ No newline at end of file diff --git a/src/RTTL.py b/src/RTTL.py deleted file mode 100644 index a27ab94..0000000 --- a/src/RTTL.py +++ /dev/null @@ -1,61 +0,0 @@ -''' -Created on 12 Ara 2010 - -@author: melih -''' - -def parse(fileName): - file = open(fileName) - songList = list() - - - for line in file: - line = line.rstrip() - noteList = list() - parts = line.split(":") - name = parts[0] - defaults = parts[1] - notes = parts[2] - - - defaults = defaults.split(",") - defaultDuration = int(defaults[0].split("=")[1]) - defaultOctave = int(defaults[1].split("=")[1]) - bpm = int(defaults[2].split("=")[1]) - - - notes = notes.split(",") - for note in notes: - note = note.upper() - noteDuration = defaultDuration - noteOctave = defaultOctave - if note[0].isdigit(): - if note[1].isdigit(): - noteDuration = int(note[:2]) - note = note[2:] - else: - noteDuration = int(note[0]) - note = note[1:] - if note[len(note) - 1].isdigit(): - noteOctave = int(note[len(note) - 1]) - note = note[0:len(note) - 1] - - if note.endswith("."): - noteDuration = noteDuration * 1.5 - note = note[0:len(note) - 1] - if note == "P": - note = None - - noteList.append((noteDuration, note, noteOctave)) - - rttl = RTTL() - rttl.name = name - rttl.notes = noteList - rttl.bpm = bpm - songList.append(rttl) - - return songList - -class RTTL: - name = "" - \ No newline at end of file diff --git a/src/NN.py b/src/brain/NN.py similarity index 100% rename from src/NN.py rename to src/brain/NN.py diff --git a/src/evolution9/midi/__init__.py b/src/brain/__init__.py similarity index 100% rename from src/evolution9/midi/__init__.py rename to src/brain/__init__.py diff --git a/src/evolution9/midi/MidiFile3.py b/src/evolution9/midi/MidiFile3.py deleted file mode 100644 index 31dcf24..0000000 --- a/src/evolution9/midi/MidiFile3.py +++ /dev/null @@ -1,1007 +0,0 @@ -#----------------------------------------------------------------------------- -# Name: MidiFile.py -# Purpose: MIDI file manipulation utilities -# -# Author: Mark Conway Wirt <emergentmusics) at (gmail . com> -# -# Created: 2008/04/17 -# Copyright: (c) 2009 Mark Conway Wirt -# License: Please see License.txt for the terms under which this -# software is distributed. -#----------------------------------------------------------------------------- - -import sys, math, struct - -# TICKSPERBEAT is the number of "ticks" (time measurement in the MIDI file) that -# corresponds to one beat. This number is somewhat arbitrary, but should be chosen -# to provide adequate temporal resolution. - -TICKSPERBEAT = 128 - -controllerEventTypes = { - 'pan' : 0x0a - } -class MIDIEvent: - ''' - The class to contain the MIDI Event (placed on MIDIEventList. - ''' - def __init__(self): - self.type='unknown' - self.time=0 - self.ord = 0 - - def __lt__(self, other): - ''' Sorting function for events.''' - if self.time < other.time: - return True - elif self.time > other.time: - return False - else: - if self.ord < other.ord: - return True - elif self.ord > other.ord: - return False - else: - return False - - def __cmp__(self, other): - ''' Sorting function for events.''' - if self.time < other.time: - return -1 - elif self.time > other.time: - return 1 - else: - if self.ord < other.ord: - return -1 - elif self.ord > other.ord: - return 1 - else: - return 0 - -class GenericEvent(): - '''The event class from which specific events are derived - ''' - def __init__(self,time): - self.time = time - self.type = 'Unknown' - - - - def __eq__(self, other): - ''' - Equality operator for Generic Events and derived classes. - - In the processing of the event list, we have need to remove duplicates. To do this - we rely on the fact that the classes are hashable, and must therefore have an - equality operator (__hash__() and __eq__() must both be defined). - - This is the most embarrassing portion of the code, and anyone who knows about OO - programming would find this almost unbelievable. Here we have a base class that - knows specifics about derived classes, thus breaking the very spirit of - OO programming. - - I suppose I should go back and restructure the code, perhaps removing the derived - classes altogether. At some point perhaps I will. - ''' - if self.time != other.time or self.type != other.type: - return False - - # What follows is code that encodes the concept of equality for each derived - # class. Believe it f you dare. - - if self.type == 'note': - if self.pitch != other.pitch or self.channel != other.channel: - return False - if self.type == 'tempo': - if self.tempo != other.tempo: - return False - if self.type == 'programChange': - if self.programNumber != other.programNumber or self.channel != other.channel: - return False - if self.type == 'trackName': - if self.trackName != other.trackName: - return False - if self.type == 'controllerEvent': - if self.parameter1 != other.parameter1 or \ - self.parameter2 != other.parameter2 or \ - self.channel != other.channel or \ - self.eventType != other.eventType: - return False - - if self.type == 'SysEx': - if self.manID != other.manID: - return False - - if self.type == 'UniversalSysEx': - if self.code != other.code or\ - self.subcode != other.subcode or \ - self.sysExChannel != other.sysExChannel: - return False - - return True - - def __hash__(self): - ''' - Return a hash code for the object. - - This is needed for the removal of duplicate objects from the event list. The only - real requirement for the algorithm is that the hash of equal objects must be equal. - There is probably great opportunity for improvements in the hashing function. - ''' - # Robert Jenkin's 32 bit hash. - a = int(self.time) - a = (a+0x7ed55d16) + (a<<12) - a = (a^0xc761c23c) ^ (a>>19) - a = (a+0x165667b1) + (a<<5) - a = (a+0xd3a2646c) ^ (a<<9) - a = (a+0xfd7046c5) + (a<<3) - a = (a^0xb55a4f09) ^ (a>>16) - return a - -class MIDITrack: - '''A class that encapsulates a MIDI track - ''' - # Nested class definitions. - - class note(GenericEvent): - '''A class that encapsulates a note - ''' - def __init__(self,channel, pitch,time,duration,volume): - - GenericEvent.__init__(self,time) - self.pitch = pitch - self.duration = duration - self.volume = volume - self.type = 'note' - self.channel = channel - - def compare(self, other): - '''Compare two notes for equality. - ''' - if self.pitch == other.pitch and \ - self.time == other.time and \ - self.duration == other.duration and \ - self.volume == other.volume and \ - self.type == other.type and \ - self.channel == other.channel: - return True - else: - return False - - - class tempo(GenericEvent): - '''A class that encapsulates a tempo meta-event - ''' - def __init__(self,time,tempo): - - GenericEvent.__init__(self,time) - self.type = 'tempo' - self.tempo = int(60000000 / tempo) - - class programChange(GenericEvent): - '''A class that encapsulates a program change event. - ''' - - def __init__(self, channel, time, programNumber): - GenericEvent.__init__(self, time,) - self.type = 'programChange' - self.programNumber = programNumber - self.channel = channel - - class SysExEvent(GenericEvent): - '''A class that encapsulates a System Exclusive event. - ''' - - def __init__(self, time, manID, payload): - GenericEvent.__init__(self, time,) - self.type = 'SysEx' - self.manID = manID - self.payload = payload - - class UniversalSysExEvent(GenericEvent): - '''A class that encapsulates a Universal System Exclusive event. - ''' - - def __init__(self, time, realTime, sysExChannel, code, subcode, payload): - GenericEvent.__init__(self, time,) - self.type = 'UniversalSysEx' - self.realTime = realTime - self.sysExChannel = sysExChannel - self.code = code - self.subcode = subcode - self.payload = payload - - class ControllerEvent(GenericEvent): - '''A class that encapsulates a program change event. - ''' - - def __init__(self, channel, time, eventType, parameter1,): - GenericEvent.__init__(self, time,) - self.type = 'controllerEvent' - self.parameter1 = parameter1 - self.channel = channel - self.eventType = eventType - - class trackName(GenericEvent): - '''A class that encapsulates a program change event. - ''' - - def __init__(self, time, trackName): - GenericEvent.__init__(self, time,) - self.type = 'trackName' - self.trackName = trackName - - - def __init__(self, removeDuplicates, deinterleave): - '''Initialize the MIDITrack object. - ''' - self.headerString = struct.pack('cccc','M','T','r','k') - self.dataLength = 0 # Is calculated after the data is in place - self.MIDIdata = b"" - self.closed = False - self.eventList = [] - self.MIDIEventList = [] - self.remdep = removeDuplicates - self.deinterleave = deinterleave - - def addNoteByNumber(self,channel, pitch,time,duration,volume): - '''Add a note by chromatic MIDI number - ''' - self.eventList.append(MIDITrack.note(channel, pitch,time,duration,volume)) - - def addControllerEvent(self,channel,time,eventType, paramerter1): - ''' - Add a controller event. - ''' - - self.eventList.append(MIDITrack.ControllerEvent(channel,time,eventType, \ - paramerter1)) - - def addTempo(self,time,tempo): - ''' - Add a tempo change (or set) event. - ''' - self.eventList.append(MIDITrack.tempo(time,tempo)) - - def addSysEx(self,time,manID, payload): - ''' - Add a SysEx event. - ''' - self.eventList.append(MIDITrack.SysExEvent(time, manID, payload)) - - def addUniversalSysEx(self,time,code, subcode, payload, sysExChannel=0x7F, \ - realTime=False): - ''' - Add a Universal SysEx event. - ''' - self.eventList.append(MIDITrack.UniversalSysExEvent(time, realTime, \ - sysExChannel, code, subcode, payload)) - - def addProgramChange(self,channel, time, program): - ''' - Add a program change event. - ''' - self.eventList.append(MIDITrack.programChange(channel, time, program)) - - def addTrackName(self,time,trackName): - ''' - Add a track name event. - ''' - self.eventList.append(MIDITrack.trackName(time,trackName)) - - def changeNoteTuning(self, tunings, sysExChannel=0x7F, realTime=False, \ - tuningProgam=0): - '''Change the tuning of MIDI notes - ''' - payload = struct.pack('>B', tuningProgam) - payload = payload + struct.pack('>B', len(tunings)) - for (noteNumber, frequency) in tunings: - payload = payload + struct.pack('>B', noteNumber) - MIDIFreqency = frequencyTransform(frequency) - for byte in MIDIFreqency: - payload = payload + struct.pack('>B', byte) - - self.eventList.append(MIDITrack.UniversalSysExEvent(0, realTime, sysExChannel,\ - 8, 2, payload)) - - def processEventList(self): - ''' - Process the event list, creating a MIDIEventList - - For each item in the event list, one or more events in the MIDIEvent - list are created. - ''' - - # Loop over all items in the eventList - - for thing in self.eventList: - if thing.type == 'note': - event = MIDIEvent() - event.type = "NoteOn" - event.time = thing.time * TICKSPERBEAT - event.pitch = thing.pitch - event.volume = thing.volume - event.channel = thing.channel - event.ord = 3 - self.MIDIEventList.append(event) - - event = MIDIEvent() - event.type = "NoteOff" - event.time = (thing.time + thing.duration) * TICKSPERBEAT - event.pitch = thing.pitch - event.volume = thing.volume - event.channel = thing.channel - event.ord = 2 - self.MIDIEventList.append(event) - - elif thing.type == 'tempo': - event = MIDIEvent() - event.type = "Tempo" - event.time = thing.time * TICKSPERBEAT - event.tempo = thing.tempo - event.ord = 3 - self.MIDIEventList.append(event) - - elif thing.type == 'programChange': - event = MIDIEvent() - event.type = "ProgramChange" - event.time = thing.time * TICKSPERBEAT - event.programNumber = thing.programNumber - event.channel = thing.channel - event.ord = 1 - self.MIDIEventList.append(event) - - elif thing.type == 'trackName': - event = MIDIEvent() - event.type = "TrackName" - event.time = thing.time * TICKSPERBEAT - event.trackName = thing.trackName - event.ord = 0 - self.MIDIEventList.append(event) - - elif thing.type == 'controllerEvent': - event = MIDIEvent() - event.type = "ControllerEvent" - event.time = thing.time * TICKSPERBEAT - event.eventType = thing.eventType - event.channel = thing.channel - event.paramerter1 = thing.parameter1 - event.ord = 1 - self.MIDIEventList.append(event) - - elif thing.type == 'SysEx': - event = MIDIEvent() - event.type = "SysEx" - event.time = thing.time * TICKSPERBEAT - event.manID = thing.manID - event.payload = thing.payload - event.ord = 1 - self.MIDIEventList.append(event) - - elif thing.type == 'UniversalSysEx': - event = MIDIEvent() - event.type = "UniversalSysEx" - event.realTime = thing.realTime - event.sysExChannel = thing.sysExChannel - event.time = thing.time * TICKSPERBEAT - event.code = thing.code - event.subcode = thing.subcode - event.payload = thing.payload - event.ord = 1 - self.MIDIEventList.append(event) - - else: - print ("Error in MIDITrack: Unknown event type") - sys.exit(2) - - # Assumptions in the code expect the list to be time-sorted. - # self.MIDIEventList.sort(lambda x, y: x.time - y.time) - - self.MIDIEventList.sort(key=lambda x: (x.time)) - - if self.deinterleave: - self.deInterleaveNotes() - - def removeDuplicates(self): - ''' - Remove duplicates from the eventList. - - This function will remove duplicates from the eventList. This is necessary - because we the MIDI event stream can become confused otherwise. - ''' - - # For this algorithm to work, the events in the eventList must be hashable - # (that is, they must have a __hash__() and __eq__() function defined). - - tempDict = {} - for item in self.eventList: - tempDict[item] = 1 - - self.eventList = list(tempDict.keys()) - - # Sort on type, them on time. Necessary because keys() has no requirement to return - # things in any order. - - self.eventList.sort(key=lambda x: (x.type)) - self.eventList.sort(key=lambda x: (x.time)) #A bit of a hack. - - def closeTrack(self): - '''Called to close a track before writing - - This function should be called to "close a track," that is to - prepare the actual data stream for writing. Duplicate events are - removed from the eventList, and the MIDIEventList is created. - - Called by the parent MIDIFile object. - ''' - - if self.closed == True: - return - self.closed = True - - if self.remdep: - self.removeDuplicates() - - - self.processEventList() - - def writeMIDIStream(self): - ''' - Write the meta data and note data to the packed MIDI stream. - ''' - - #Process the events in the eventList - - self.writeEventsToStream() - - # Write MIDI close event. - - self.MIDIdata = self.MIDIdata + struct.pack('BBBB',0x00,0xFF, \ - 0x2F,0x00) - - # Calculate the entire length of the data and write to the header - - self.dataLength = struct.pack('>L',len(self.MIDIdata)) - - def writeEventsToStream(self): - ''' - Write the events in MIDIEvents to the MIDI stream. - ''' - - for event in self.MIDIEventList: - if event.type == "NoteOn": - code = 0x9 << 4 | event.channel - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B',code) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.pitch) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.volume) - elif event.type == "NoteOff": - code = 0x8 << 4 | event.channel - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B',code) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.pitch) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.volume) - elif event.type == "Tempo": - code = 0xFF - subcode = 0x51 - fourbite = struct.pack('>L', event.tempo) - threebite = fourbite[1:4] # Just discard the MSB - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B',code) - self.MIDIdata = self.MIDIdata + struct.pack('>B',subcode) - self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x03) # Data length: 3 - self.MIDIdata = self.MIDIdata + threebite - elif event.type == 'ProgramChange': - code = 0xC << 4 | event.channel - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B',code) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.programNumber) - elif event.type == 'TrackName': - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('B',0xFF) # Meta-event - self.MIDIdata = self.MIDIdata + struct.pack('B',0X03) # Event Type - dataLength = len(event.trackName) - dataLenghtVar = writeVarLength(dataLength) - for i in range(0,len(dataLenghtVar)): - self.MIDIdata = self.MIDIdata + struct.pack("b",dataLenghtVar[i]) - self.MIDIdata = self.MIDIdata + event.trackName.encode() - elif event.type == "ControllerEvent": - code = 0xB << 4 | event.channel - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B',code) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.eventType) - self.MIDIdata = self.MIDIdata + struct.pack('>B',event.paramerter1) - elif event.type == "SysEx": - code = 0xF0 - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B', code) - - payloadLength = writeVarLength(len(event.payload)+2) - for lenByte in payloadLength: - self.MIDIdata = self.MIDIdata + struct.pack('>B',lenByte) - - self.MIDIdata = self.MIDIdata + struct.pack('>B', event.manID) - self.MIDIdata = self.MIDIdata + event.payload - self.MIDIdata = self.MIDIdata + struct.pack('>B',0xF7) - elif event.type == "UniversalSysEx": - code = 0xF0 - varTime = writeVarLength(event.time) - for timeByte in varTime: - self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) - self.MIDIdata = self.MIDIdata + struct.pack('>B', code) - - # Do we need to add a length? - payloadLength = writeVarLength(len(event.payload)+5) - for lenByte in payloadLength: - self.MIDIdata = self.MIDIdata + struct.pack('>B',lenByte) - - if event.realTime : - self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x7F) - else: - self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x7E) - - self.MIDIdata = self.MIDIdata + struct.pack('>B', event.sysExChannel) - self.MIDIdata = self.MIDIdata + struct.pack('>B', event.code) - self.MIDIdata = self.MIDIdata + struct.pack('>B', event.subcode) - self.MIDIdata = self.MIDIdata + event.payload - self.MIDIdata = self.MIDIdata + struct.pack('>B',0xF7) - - def deInterleaveNotes(self): - '''Correct Interleaved notes. - - Because we are writing multiple notes in no particular order, we - can have notes which are interleaved with respect to their start - and stop times. This method will correct that. It expects that the - MIDIEventList has been time-ordered. - ''' - - tempEventList = [] - stack = {} - - for event in self.MIDIEventList: - - if event.type == 'NoteOn': - if str(event.pitch)+str(event.channel) in stack: - stack[str(event.pitch)+str(event.channel)].append(event.time) - else: - stack[str(event.pitch)+str(event.channel)] = [event.time] - tempEventList.append(event) - elif event.type == 'NoteOff': - if len(stack[str(event.pitch)+str(event.channel)]) > 1: - event.time = stack[str(event.pitch)+str(event.channel)].pop() - tempEventList.append(event) - else: - stack[str(event.pitch)+str(event.channel)].pop() - tempEventList.append(event) - else: - tempEventList.append(event) - - self.MIDIEventList = tempEventList - - # A little trickery here. We want to make sure that NoteOff events appear - # before NoteOn events, so we'll do two sorts -- on on type, one on time. - # This may have to be revisited, as it makes assumptions about how - # the internal sort works, and is in essence creating a sort on a primary - # and secondary key. - - self.MIDIEventList.sort(key=lambda x: (x.type)) - self.MIDIEventList.sort(key=lambda x: (x.time)) - - def adjustTime(self,origin): - ''' - Adjust Times to be relative, and zero-origined - ''' - - if len(self.MIDIEventList) == 0: - return - tempEventList = [] - - runningTime = 0 - - for event in self.MIDIEventList: - adjustedTime = event.time - origin - event.time = adjustedTime - runningTime - runningTime = adjustedTime - tempEventList.append(event) - - self.MIDIEventList = tempEventList - - def writeTrack(self,fileHandle): - ''' - Write track to disk. - ''' - - if not self.closed: - self.closeTrack() - - fileHandle.write(self.headerString) - fileHandle.write(self.dataLength) - fileHandle.write(self.MIDIdata) - - -class MIDIHeader: - ''' - Class to encapsulate the MIDI header structure. - - This class encapsulates a MIDI header structure. It isn't used for much, - but it will create the appropriately packed identifier string that all - MIDI files should contain. It is used by the MIDIFile class to create a - complete and well formed MIDI pattern. - - ''' - def __init__(self,numTracks): - ''' Initialize the data structures - ''' - self.headerString = struct.pack('cccc','M','T','h','d') - self.headerSize = struct.pack('>L',6) - # Format 1 = multi-track file - self.format = struct.pack('>H',1) - self.numTracks = struct.pack('>H',numTracks) - self.ticksPerBeat = struct.pack('>H',TICKSPERBEAT) - - - def writeFile(self,fileHandle): - fileHandle.write(self.headerString) - fileHandle.write(self.headerSize) - fileHandle.write(self.format) - fileHandle.write(self.numTracks) - fileHandle.write(self.ticksPerBeat) - -class MIDIFile: - '''Class that represents a full, well-formed MIDI pattern. - - This is a container object that contains a header, one or more tracks, - and the data associated with a proper and well-formed MIDI pattern. - - Calling: - - MyMIDI = MidiFile(tracks, removeDuplicates=True, deinterleave=True) - - normally - - MyMIDI = MidiFile(tracks) - - Arguments: - - tracks: The number of tracks this object contains - - removeDuplicates: If true (the default), the software will remove duplicate - events which have been added. For example, two notes at the same channel, - time, pitch, and duration would be considered duplicate. - - deinterleave: If True (the default), overlapping notes (same pitch, same - channel) will be modified so that they do not overlap. Otherwise the sequencing - software will need to figure out how to interpret NoteOff events upon playback. - ''' - - def __init__(self, numTracks, removeDuplicates=True, deinterleave=True): - ''' - Initialize the class - ''' - self.header = MIDIHeader(numTracks) - - self.tracks = list() - self.numTracks = numTracks - self.closed = False - - for i in range(0,numTracks): - self.tracks.append(MIDITrack(removeDuplicates, deinterleave)) - - - # Public Functions. These (for the most part) wrap the MIDITrack functions, where most - # Processing takes place. - - def addNote(self,track, channel, pitch,time,duration,volume): - """ - Add notes to the MIDIFile object - - Use: - MyMIDI.addNotes(track,channel,pitch,time, duration, volume) - - Arguments: - track: The track to which the note is added. - channel: the MIDI channel to assign to the note. [Integer, 0-15] - pitch: the MIDI pitch number [Integer, 0-127]. - time: the time (in beats) at which the note sounds [Float]. - duration: the duration of the note (in beats) [Float]. - volume: the volume (velocity) of the note. [Integer, 0-127]. - """ - self.tracks[track].addNoteByNumber(channel, pitch, time, duration, volume) - - def addTrackName(self,track, time,trackName): - """ - Add a track name to a MIDI track. - - Use: - MyMIDI.addTrackName(track,time,trackName) - - Argument: - track: The track to which the name is added. [Integer, 0-127]. - time: The time at which the track name is added, in beats [Float]. - trackName: The track name. [String]. - """ - self.tracks[track].addTrackName(time,trackName) - - def addTempo(self,track, time,tempo): - """ - Add a tempo event. - - Use: - MyMIDI.addTempo(track, time, tempo) - - Arguments: - track: The track to which the event is added. [Integer, 0-127]. - time: The time at which the event is added, in beats. [Float]. - tempo: The tempo, in Beats per Minute. [Integer] - """ - self.tracks[track].addTempo(time,tempo) - - def addProgramChange(self,track, channel, time, program): - """ - Add a MIDI program change event. - - Use: - MyMIDI.addProgramChange(track,channel, time, program) - - Arguments: - track: The track to which the event is added. [Integer, 0-127]. - channel: The channel the event is assigned to. [Integer, 0-15]. - time: The time at which the event is added, in beats. [Float]. - program: the program number. [Integer, 0-127]. - """ - self.tracks[track].addProgramChange(channel, time, program) - - def addControllerEvent(self,track, channel,time,eventType, paramerter1): - """ - Add a MIDI controller event. - - Use: - MyMIDI.addControllerEvent(track, channel, time, eventType, parameter1) - - Arguments: - track: The track to which the event is added. [Integer, 0-127]. - channel: The channel the event is assigned to. [Integer, 0-15]. - time: The time at which the event is added, in beats. [Float]. - eventType: the controller event type. - parameter1: The event's parameter. The meaning of which varies by event type. - """ - self.tracks[track].addControllerEvent(channel,time,eventType, paramerter1) - - def changeNoteTuning(self, track, tunings, sysExChannel=0x7F, \ - realTime=False, tuningProgam=0): - """ - Change a note's tuning using SysEx change tuning program. - - Use: - MyMIDI.changeNoteTuning(track,[tunings],realTime=False, tuningProgram=0) - - Arguments: - track: The track to which the event is added. [Integer, 0-127]. - tunings: A list of tuples in the form (pitchNumber, frequency). - [[(Integer,Float]] - realTime: Boolean which sets the real-time flag. Defaults to false. - sysExChannel: do note use (see below). - tuningProgram: Tuning program to assign. Defaults to zero. [Integer, 0-127] - - In general the sysExChannel should not be changed (parameter will be depreciated). - - Also note that many software packages and hardware packages do not implement - this standard! - """ - self.tracks[track].changeNoteTuning(tunings, sysExChannel, realTime,\ - tuningProgam) - - def writeFile(self,fileHandle): - ''' - Write the MIDI File. - - Use: - MyMIDI.writeFile(filehandle) - - Arguments: - filehandle: a file handle that has been opened for binary writing. - ''' - - self.header.writeFile(fileHandle) - - #Close the tracks and have them create the MIDI event data structures. - self.close() - - #Write the MIDI Events to file. - for i in range(0,self.numTracks): - self.tracks[i].writeTrack(fileHandle) - - def addSysEx(self,track, time, manID, payload): - """ - Add a SysEx event - - Use: - MyMIDI.addSysEx(track,time,ID,payload) - - Arguments: - track: The track to which the event is added. [Integer, 0-127]. - time: The time at which the event is added, in beats. [Float]. - ID: The SysEx ID number - payload: the event payload. - - Note: This is a low-level MIDI function, so care must be used in - constructing the payload. It is recommended that higher-level helper - functions be written to wrap this function and construct the payload if - a developer finds him or herself using the function heavily. - """ - self.tracks[track].addSysEx(time,manID, payload) - - def addUniversalSysEx(self,track, time,code, subcode, payload, \ - sysExChannel=0x7F, realTime=False): - """ - Add a Universal SysEx event. - - Use: - MyMIDI.addUniversalSysEx(track, time, code, subcode, payload,\ - sysExChannel=0x7f, realTime=False) - - Arguments: - track: The track to which the event is added. [Integer, 0-127]. - time: The time at which the event is added, in beats. [Float]. - code: The even code. [Integer] - subcode The event sub-code [Integer] - payload: The event payload. [Binary string] - sysExChannel: The SysEx channel. - realTime: Sets the real-time flag. Defaults to zero. - - Note: This is a low-level MIDI function, so care must be used in - constructing the payload. It is recommended that higher-level helper - functions be written to wrap this function and construct the payload if - a developer finds him or herself using the function heavily. As an example - of such a helper function, see the changeNoteTuning function, both here and - in MIDITrack. - """ - - self.tracks[track].addUniversalSysEx(time,code, subcode, payload, sysExChannel,\ - realTime) - - def shiftTracks(self, offset=0): - """Shift tracks to be zero-origined, or origined at offset. - - Note that the shifting of the time in the tracks uses the MIDIEventList -- in other - words it is assumed to be called in the stage where the MIDIEventList has been - created. This function, however, it meant to operate on the eventList itself. - """ - origin = 1000000 # A little silly, but we'll assume big enough - - for track in self.tracks: - if len(track.eventList) > 0: - for event in track.eventList: - if event.time < origin: - origin = event.time - - for track in self.tracks: - tempEventList = [] - #runningTime = 0 - - for event in track.eventList: - adjustedTime = event.time - origin - #event.time = adjustedTime - runningTime + offset - event.time = adjustedTime + offset - #runningTime = adjustedTime - tempEventList.append(event) - - track.eventList = tempEventList - - #End Public Functions ######################## - - def close(self): - '''Close the MIDIFile for further writing. - - To close the File for events, we must close the tracks, adjust the time to be - zero-origined, and have the tracks write to their MIDI Stream data structure. - ''' - - if self.closed == True: - return - - for i in range(0,self.numTracks): - self.tracks[i].closeTrack() - # We want things like program changes to come before notes when they are at the - # same time, so we sort the MIDI events by their ordinality - self.tracks[i].MIDIEventList.sort() - - origin = self.findOrigin() - - for i in range(0,self.numTracks): - self.tracks[i].adjustTime(origin) - self.tracks[i].writeMIDIStream() - - self.closed = True - - - def findOrigin(self): - '''Find the earliest time in the file's tracks.append. - ''' - origin = 1000000 # A little silly, but we'll assume big enough - - # Note: This code assumes that the MIDIEventList has been sorted, so this should be insured - # before it is called. It is probably a poor design to do this. - # TODO: -- Consider making this less efficient but more robust by not assuming the list to be sorted. - - for track in self.tracks: - if len(track.MIDIEventList) > 0: - if track.MIDIEventList[0].time < origin: - origin = track.MIDIEventList[0].time - - - return origin - -def writeVarLength(i): - '''Accept an input, and write a MIDI-compatible variable length stream - - The MIDI format is a little strange, and makes use of so-called variable - length quantities. These quantities are a stream of bytes. If the most - significant bit is 1, then more bytes follow. If it is zero, then the - byte in question is the last in the stream - ''' - input = int(i) - output = [0,0,0,0] - reversed = [0,0,0,0] - count = 0 - result = input & 0x7F - output[count] = result - count = count + 1 - input = input >> 7 - while input > 0: - result = input & 0x7F - result = result | 0x80 - output[count] = result - count = count + 1 - input = input >> 7 - - reversed[0] = output[3] - reversed[1] = output[2] - reversed[2] = output[1] - reversed[3] = output[0] - return reversed[4-count:4] - -def frequencyTransform(freq): - '''Returns a three-byte transform of a frequencyTransform - ''' - resolution = 16384 - freq = float(freq) - dollars = 69 + 12 * math.log(freq/(float(440)), 2) - firstByte = int(dollars) - lowerFreq = 440 * pow(2.0, ((float(firstByte) - 69.0)/12.0)) - if freq != lowerFreq: - centDif = 1200 * math.log( (freq/lowerFreq), 2) - else: - centDif = 0 - cents = round(centDif/100 * resolution) # round? - secondByte = min([int(cents)>>7, 0x7F]) - thirdByte = cents - (secondByte << 7) - thirdByte = min([thirdByte, 0x7f]) - if thirdByte == 0x7f and secondByte == 0x7F and firstByte == 0x7F: - thirdByte = 0x7e - - thirdByte = int(thirdByte) - return [firstByte, secondByte, thirdByte] - -def returnFrequency(freqBytes): - '''The reverse of frequencyTransform. Given a byte stream, return a frequency. - ''' - resolution = 16384.0 - baseFrequency = 440 * pow(2.0, (float(freqBytes[0]-69.0)/12.0)) - frac = (float((int(freqBytes[1]) << 7) + int(freqBytes[2])) * 100.0) / resolution - frequency = baseFrequency * pow(2.0, frac/1200.0) - return frequency diff --git a/src/evolution9/midi/midiActions.py b/src/evolution9/midi/midiActions.py deleted file mode 100644 index 396594e..0000000 --- a/src/evolution9/midi/midiActions.py +++ /dev/null @@ -1,27 +0,0 @@ -''' -Created on Oct 11, 2010 - -@author: cagatay.yuksel -''' - -from evolution9.midi.MidiFile3 import MIDIFile -from constants import OUTPUT_DIR - -def createMIDI(filename, notes): - midi = MIDIFile(1) - track = 0 - time = 0 - tempo = 200 - channel = 0 - volume = 100 - - midi.addTrackName(track, time, "track") - midi.addTempo(track, time, tempo) - - for duration, pitch in notes: - midi.addNote(track, channel, pitch, time, duration, volume) - time += duration - - fileHandle = open(OUTPUT_DIR + filename, "wb") - midi.writeFile(fileHandle) - fileHandle.close() diff --git a/src/evolve.py b/src/evolve.py new file mode 100755 index 0000000..b3b1c8a --- /dev/null +++ b/src/evolve.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +''' +Created on Oct 6, 2010 + +@author: cagatay +''' + +from random import randrange +from random import random + +from evolution9.midi.midiActions import createMIDI +from evolution9.evolution.storage import db +from pybrain.tools.shortcuts import buildNetwork +from mingus.midi.MidiFileIn import MIDI_to_Composition +from mingus.midi.MidiFileOut import write_Track +from mingus.containers import * +from pybrain.supervised.trainers import BackpropTrainer +from pybrain.datasets import SupervisedDataSet +import mingus.core.notes as notes +import mingus.core.value as value +import RTTL +import os +import constants +from NN import NN + + + +if __name__ == '__main__': + + ''' + currentNN = NN("yeni",3,1) + + for song in songList: + currentNN.addSong( song ) + + currentNN.train() + + currentNN.saveNetworkToFile() + + #currentNN.readNetworkFromFile() + + songList = RTTL.parse(constants.INPUT_DIR + "metallica.txt") + + sonuc = currentNN.fitness( songList[0] ) + + print sonuc + + sonuc = currentNN.fitness( songList[1] ) + + print sonuc + + songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") + + sonuc = currentNN.fitness( songList[6] ) + + print sonuc + + ''' + + songs = RTTL.parse(constants.INPUT_DIR + "beatles.txt") + for song in songs: + track = Track() + + for n in song.track: + track.add_notes(n.note, value.dots(n.duration, n.dot)) + write_Track(constants.OUTPUT_DIR + song.name + ".mid", track, song.tempo) + +# storage = db.Database() +# storage.initDatabase() +# storage.printAll() +# composition = list() diff --git a/src/main.py b/src/main.py deleted file mode 100644 index 82f1995..0000000 --- a/src/main.py +++ /dev/null @@ -1,117 +0,0 @@ -''' -Created on Oct 6, 2010 - -@author: cagatay.yuksel -''' - -from random import randrange -from random import random - -from evolution9.midi.midiActions import createMIDI -from evolution9.evolution.storage import db -from pybrain.tools.shortcuts import buildNetwork -from mingus.midi.MidiFileIn import MIDI_to_Composition -from mingus.midi.MidiFileOut import write_Composition -from mingus.containers import * -from pybrain.supervised.trainers import BackpropTrainer -from pybrain.datasets import SupervisedDataSet -import mingus.core.notes as notes -import RTTL -import os -import constants -from NN import NN - - - -if __name__ == '__main__': - songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") - - - currentNN = NN("yeni",3,1) - - for song in songList: - currentNN.addSong( song ) - - currentNN.train() - - currentNN.saveNetworkToFile() - - #currentNN.readNetworkFromFile() - - songList = RTTL.parse(constants.INPUT_DIR + "metallica.txt") - - sonuc = currentNN.fitness( songList[0] ) - - print sonuc - - sonuc = currentNN.fitness( songList[1] ) - - print sonuc - - songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") - - sonuc = currentNN.fitness( songList[6] ) - - print sonuc - - - - - - - -# for song in list: -# track = Track() -# -# for note in song.notes: -# if not note[1]: -# track.add_notes(None, note[0]) -# else: -# currentNote = int(Note(note[1], note[2])) -# track.add_notes(Note(note[1], note[2]), note[0]) -# composition = Composition() -# composition.add_track(track) -# composition.set_title(song.name) -# write_Composition(constants.OUTPUT_DIR + song.name + ".mid", composition, song.bpm) -# defDuration = 4 -# defOctave = 5 -# beat = 180 -# -# track = Track() -# track.add_notes("C#", 8) -# track.add_notes("D", 8) -# track.add_notes("C#", 8) -# track.add_notes("E", defDuration) -# track.add_notes(None, defDuration) -# track.add_notes("E", defDuration) -# track.add_notes(None, 8) -# track.add_notes("E", defDuration) -# track.add_notes(None, defDuration) -# track.add_notes("E", 8) -# -# composition = Composition() -# composition.add_track(track) - -# write_Composition(constants.OUTPUT_DIR + "1.mid", composition, beat) -# midiFiles = os.listdir(constants.INPUT_DIR) -# compositions = list() -# -# for fileName in midiFiles: -# -# (composition, beat) = MIDI_to_Composition(constants.INPUT_DIR + fileName) -# #composition.add_note("C#") -# write_Composition(constants.OUTPUT_DIR + fileName, composition, beat) -# #compositions.append(composition) -# - -# storage = db.Database() -# storage.initDatabase() -# storage.printAll() -# composition = list() -# -# -# for i in range(10): -# pitch = randrange(40, 80) -# duration = random() -# composition.append((duration, pitch)) - diff --git a/src/train.py b/src/train.py new file mode 100755 index 0000000..e69de29 diff --git a/src/util/RTTL.py b/src/util/RTTL.py new file mode 100644 index 0000000..76e9ca5 --- /dev/null +++ b/src/util/RTTL.py @@ -0,0 +1,67 @@ +''' +Created on 12 Ara 2010 + +@author: melih +''' + +def parse(fileName): + file = open(fileName) + songs = list() + + + for line in file: + line = line.rstrip() + track = list() + parts = line.split(":") + name = parts[0] + defaults = parts[1] + notes = parts[2] + + + defaults = defaults.split(",") + defaultDuration = int(defaults[0].split("=")[1]) + defaultOctave = int(defaults[1].split("=")[1]) + tempo = int(defaults[2].split("=")[1]) + + + notes = notes.split(",") + for n in notes: + n = n.upper() + duration = defaultDuration + octave = defaultOctave + dot = 0 + if n[0].isdigit(): + if n[1].isdigit(): + duration = int(n[:2]) + n = n[2:] + else: + duration = int(n[0]) + n = n[1:] + if n[len(n) - 1].isdigit(): + octave = int(n[len(n) - 1]) + n = n[0:len(n) - 1] + + if n.endswith("."): + dot = 1 + n = n[0:len(n) - 1] + if n == "P": + n = None + + track.append(note(duration, n, octave, dot)) + + songs.append(song(name, track, tempo)) + + return songs + +class song: + def __init__(self, name, track, tempo): + self.name = name + self.track = track + self.tempo = tempo +class note: + def __init__(self, duration, note, octave, dot): + self.duration = duration + self.note = note + if self.note: + self.note += '-' + str(octave) + self.dot = dot diff --git a/src/util/__init__.py b/src/util/__init__.py new file mode 100644 index 0000000..e69de29
cagatay/Evolution-9
1d5a6072366069467bc8ad1adbadb2c866285c3a
fitness function tested&configured
diff --git a/inputs/metallica.txt b/inputs/metallica.txt new file mode 100644 index 0000000..1397e29 --- /dev/null +++ b/inputs/metallica.txt @@ -0,0 +1,2 @@ +idisappear:d=4,o=5,b=125:d#.,f#,2a#.,8p,8a#,8a#,a#,g#.,8p,8a#,8a#,a#,g#,8a#,8g#,f#,f#,8d#,d#.,f#,2a#.,8p,8a#,8a#,a#,g#.,8p,8a#,8a#,a#,g#,8a#,8g#,f#,f#,g#,g#,a#,b,c#6,d#6,8g#,a#.,p,a#.,c#6,8c#6,d#6,d#.6,c#6,a#,2g#,8p,8a#,8a#,a#,g#,8a#,8g#,f#,f#,d# +Vibrations:d=8,o=6,b=125:f#.,e,16d#,c#.,f#.5,g#.5,a#.5,4c#.,f#.,e,16d#,c#.,f#.5,g#.5,a#.5,4c#.,f#.,e,16d#,c#.,f#.5,g#.5,a#.5,4c#.,f#.,e,16d#,c#.,f#.5,g#.5,a#.5,c#.,4c.7,4c#.7,4d#7,g#.,g#.,4a#,1c7,4p,4d.7,4d#.7,4f7,a#.,a#.,4c7,2d.7 \ No newline at end of file diff --git a/src/NN.py b/src/NN.py index 348c9ff..30b2668 100644 --- a/src/NN.py +++ b/src/NN.py @@ -1,96 +1,144 @@ from pybrain.tools.shortcuts import buildNetwork from mingus.containers import * from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import constants import pickle +import math class NN: name = "" net = buildNetwork(1, 1, 1) inputCount = 1 outputCount = 1 + hiddenLayerNodeCount = 20 + durationPerNote = 2; + ds = SupervisedDataSet(inputCount, outputCount) - def __init__(self, _name, _inputCount, _outputCount): + def __init__(self, _name, _inputCount, _outputCount, _durationPerNote = 2): self.name= _name self.inputCount = _inputCount self.outputCount = _outputCount - self.net = buildNetwork(self.inputCount, 6, self.outputCount) + self.durationPerNote = _durationPerNote + self.net = buildNetwork(self.inputCount, self.hiddenLayerNodeCount, self.outputCount) + self.ds = SupervisedDataSet(self.inputCount, self.outputCount) def saveNetworkToFile(self): pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) def readNetworkFromFile(self): - self.net = pickle.load( self.net, open(constants.SAVE_DIR + self.name + "-" + self.net = pickle.load( open(constants.SAVE_DIR + self.name + "-" + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) + def train(self): + trainer = BackpropTrainer(self.net, self.ds, verbose=True) + + trainer.trainUntilConvergence() +# for i in range(0,5000): +# trainer.trainEpochs(1) +# print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 4, 64))[0]) +# trainer.trainEpochs(1) +# print '\tvalue after %d epochs: %.2f'%(i, self.net.activate((64, 64, 64))[0]) +# + + + def addSong(self, song): + + song = self.attachIntList( song ) + + + + i = 0 + z = 0 - def train(self, song): + for intNote in song.intList: + + if i + self.inputCount >= len( song.intList ): + break + + sampleList = list() + sampleOutputList = list() + + for j in range( 0, self.inputCount + 1 ): + + if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : + + + if( j + i + self.outputCount < len( song.intList ) ): + + for z in range( j + i , j + i + self.outputCount ): + #sampleOutputList.append( song.intList[ z ] ) + sampleOutputList.append( 1 ) + + self.ds.addSample( sampleList, sampleOutputList ) + + sampleList = list() + sampleOutputList = list() + + else: + sampleList.append( song.intList[ j + i ] ) + + i += 1 + + + + def attachIntList(self, song): currentNoteInt = 0 currentDuration = 0 currentNote = Note() - song.intList = list() for note in song.notes: if not note[1]: currentNote = None currentNoteInt = 0 currentDuration = note[0] else: currentNote = Note(note[1], note[2]) currentNoteInt = int(Note(note[1], note[2])) currentDuration = note[0] insertedDuration = 0 while insertedDuration < currentDuration: song.intList.append(currentNoteInt) insertedDuration += 2 - - - #prepare dataset - ds = SupervisedDataSet(self.inputCount, self.outputCount) - - + return song + + + def fitness(self, song): + returnValue = 0.0 + song = self.attachIntList( song ) + i = 0 z = 0 for intNote in song.intList: if i + self.inputCount >= len( song.intList ): break sampleList = list() - sampleOutputList = list() for j in range( 0, self.inputCount + 1 ): if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : if( j + i + self.outputCount < len( song.intList ) ): for z in range( j + i , j + i + self.outputCount ): - sampleOutputList.append( song.intList[ z ] ) - - ds.addSample( sampleList, sampleOutputList ) + returnValue += math.fabs( self.net.activate( sampleList )[0] - 1) sampleList = list() - sampleOutputList = list() else: sampleList.append( song.intList[ j + i ] ) i += 1 - trainer = BackpropTrainer(self.net, ds, verbose=True) - for i in range(0,5): - trainer.trainEpochs(1) - print '\tvalue after %d epochs: %.2f %.2f'%(i, self.net.activate((64, 64, 64))[0], self.net.activate((64, 64, 64))[1]) - -def fitness(self, song): - return 10 \ No newline at end of file + + return returnValue \ No newline at end of file diff --git a/src/main.py b/src/main.py index 4b0d663..82f1995 100644 --- a/src/main.py +++ b/src/main.py @@ -1,97 +1,117 @@ ''' Created on Oct 6, 2010 @author: cagatay.yuksel ''' from random import randrange from random import random from evolution9.midi.midiActions import createMIDI from evolution9.evolution.storage import db from pybrain.tools.shortcuts import buildNetwork from mingus.midi.MidiFileIn import MIDI_to_Composition from mingus.midi.MidiFileOut import write_Composition from mingus.containers import * from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet import mingus.core.notes as notes import RTTL import os import constants from NN import NN if __name__ == '__main__': songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") - currentNN = NN("yeni",3,3) + currentNN = NN("yeni",3,1) - currentNN.train(songList[0]) + for song in songList: + currentNN.addSong( song ) + + currentNN.train() currentNN.saveNetworkToFile() + #currentNN.readNetworkFromFile() + + songList = RTTL.parse(constants.INPUT_DIR + "metallica.txt") + + sonuc = currentNN.fitness( songList[0] ) + + print sonuc + + sonuc = currentNN.fitness( songList[1] ) + + print sonuc + + songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") + + sonuc = currentNN.fitness( songList[6] ) + + print sonuc # for song in list: # track = Track() # # for note in song.notes: # if not note[1]: # track.add_notes(None, note[0]) # else: # currentNote = int(Note(note[1], note[2])) # track.add_notes(Note(note[1], note[2]), note[0]) # composition = Composition() # composition.add_track(track) # composition.set_title(song.name) # write_Composition(constants.OUTPUT_DIR + song.name + ".mid", composition, song.bpm) # defDuration = 4 # defOctave = 5 # beat = 180 # # track = Track() # track.add_notes("C#", 8) # track.add_notes("D", 8) # track.add_notes("C#", 8) # track.add_notes("E", defDuration) # track.add_notes(None, defDuration) # track.add_notes("E", defDuration) # track.add_notes(None, 8) # track.add_notes("E", defDuration) # track.add_notes(None, defDuration) # track.add_notes("E", 8) # # composition = Composition() # composition.add_track(track) # write_Composition(constants.OUTPUT_DIR + "1.mid", composition, beat) # midiFiles = os.listdir(constants.INPUT_DIR) # compositions = list() # # for fileName in midiFiles: # # (composition, beat) = MIDI_to_Composition(constants.INPUT_DIR + fileName) # #composition.add_note("C#") # write_Composition(constants.OUTPUT_DIR + fileName, composition, beat) # #compositions.append(composition) # # storage = db.Database() # storage.initDatabase() # storage.printAll() # composition = list() # # # for i in range(10): # pitch = randrange(40, 80) # duration = random() # composition.append((duration, pitch))
cagatay/Evolution-9
6272aaa656f04bc1092f6b4c4b9af0f3af6f8e03
- Neural Network yapısını kaydedip daha sonra kullanmak için save klasörü yaratıldı - Neural Network ü şarkılarla eğitecek sınıf yaratıldı -
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1f57b97 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/output diff --git a/src/NN.py b/src/NN.py new file mode 100644 index 0000000..348c9ff --- /dev/null +++ b/src/NN.py @@ -0,0 +1,96 @@ +from pybrain.tools.shortcuts import buildNetwork +from mingus.containers import * +from pybrain.supervised.trainers import BackpropTrainer +from pybrain.datasets import SupervisedDataSet +import constants +import pickle + + +class NN: + name = "" + net = buildNetwork(1, 1, 1) + inputCount = 1 + outputCount = 1 + + + def __init__(self, _name, _inputCount, _outputCount): + self.name= _name + self.inputCount = _inputCount + self.outputCount = _outputCount + self.net = buildNetwork(self.inputCount, 6, self.outputCount) + + def saveNetworkToFile(self): + pickle.dump(self.net, open(constants.SAVE_DIR + self.name + "-" + + str(self.inputCount) + "-" + str(self.outputCount), "w" ) ) + + def readNetworkFromFile(self): + self.net = pickle.load( self.net, open(constants.SAVE_DIR + self.name + "-" + + str(self.inputCount) + "-" + str(self.outputCount), "r" ) ) + + + def train(self, song): + currentNoteInt = 0 + currentDuration = 0 + currentNote = Note() + + song.intList = list() + for note in song.notes: + if not note[1]: + currentNote = None + currentNoteInt = 0 + currentDuration = note[0] + else: + currentNote = Note(note[1], note[2]) + currentNoteInt = int(Note(note[1], note[2])) + currentDuration = note[0] + + insertedDuration = 0 + while insertedDuration < currentDuration: + song.intList.append(currentNoteInt) + insertedDuration += 2 + + + #prepare dataset + ds = SupervisedDataSet(self.inputCount, self.outputCount) + + + + + i = 0 + z = 0 + + for intNote in song.intList: + + if i + self.inputCount >= len( song.intList ): + break + + sampleList = list() + sampleOutputList = list() + + for j in range( 0, self.inputCount + 1 ): + + if j % self.inputCount == 0 and len( sampleList ) == self.inputCount : + + + if( j + i + self.outputCount < len( song.intList ) ): + + for z in range( j + i , j + i + self.outputCount ): + sampleOutputList.append( song.intList[ z ] ) + + ds.addSample( sampleList, sampleOutputList ) + + sampleList = list() + sampleOutputList = list() + + else: + sampleList.append( song.intList[ j + i ] ) + + i += 1 + + trainer = BackpropTrainer(self.net, ds, verbose=True) + for i in range(0,5): + trainer.trainEpochs(1) + print '\tvalue after %d epochs: %.2f %.2f'%(i, self.net.activate((64, 64, 64))[0], self.net.activate((64, 64, 64))[1]) + +def fitness(self, song): + return 10 \ No newline at end of file diff --git a/src/constants.py b/src/constants.py index 70f1e43..71081ea 100644 --- a/src/constants.py +++ b/src/constants.py @@ -1,9 +1,10 @@ ''' Created on Oct 10, 2010 @author: cagatay.yuksel ''' SQLITE_FILE = "../data/evolution9.db" OUTPUT_DIR = "../output/" -INPUT_DIR = "../inputs/" \ No newline at end of file +INPUT_DIR = "../inputs/" +SAVE_DIR = "../save/" \ No newline at end of file diff --git a/src/main.py b/src/main.py index cc0b645..4b0d663 100644 --- a/src/main.py +++ b/src/main.py @@ -1,78 +1,97 @@ ''' Created on Oct 6, 2010 @author: cagatay.yuksel ''' from random import randrange from random import random from evolution9.midi.midiActions import createMIDI from evolution9.evolution.storage import db from pybrain.tools.shortcuts import buildNetwork from mingus.midi.MidiFileIn import MIDI_to_Composition from mingus.midi.MidiFileOut import write_Composition from mingus.containers import * +from pybrain.supervised.trainers import BackpropTrainer +from pybrain.datasets import SupervisedDataSet +import mingus.core.notes as notes import RTTL import os import constants +from NN import NN if __name__ == '__main__': - list = RTTL.parse(constants.INPUT_DIR + "beatles.txt") + songList = RTTL.parse(constants.INPUT_DIR + "beatles.txt") - for song in list: - track = Track() - - for note in song.notes: - if not note[1]: - track.add_notes(None, note[0]) - else: - track.add_notes(Note(note[1], note[2]), note[0]) - composition = Composition() - composition.add_track(track) - composition.set_title(song.name) - write_Composition(constants.OUTPUT_DIR + song.name + ".mid", composition, song.bpm) + + currentNN = NN("yeni",3,3) + + currentNN.train(songList[0]) + + currentNN.saveNetworkToFile() + + + + + + + + +# for song in list: +# track = Track() +# +# for note in song.notes: +# if not note[1]: +# track.add_notes(None, note[0]) +# else: +# currentNote = int(Note(note[1], note[2])) +# track.add_notes(Note(note[1], note[2]), note[0]) +# composition = Composition() +# composition.add_track(track) +# composition.set_title(song.name) +# write_Composition(constants.OUTPUT_DIR + song.name + ".mid", composition, song.bpm) # defDuration = 4 # defOctave = 5 # beat = 180 # # track = Track() # track.add_notes("C#", 8) # track.add_notes("D", 8) # track.add_notes("C#", 8) # track.add_notes("E", defDuration) # track.add_notes(None, defDuration) # track.add_notes("E", defDuration) # track.add_notes(None, 8) # track.add_notes("E", defDuration) # track.add_notes(None, defDuration) # track.add_notes("E", 8) # # composition = Composition() # composition.add_track(track) # write_Composition(constants.OUTPUT_DIR + "1.mid", composition, beat) # midiFiles = os.listdir(constants.INPUT_DIR) # compositions = list() # # for fileName in midiFiles: # # (composition, beat) = MIDI_to_Composition(constants.INPUT_DIR + fileName) # #composition.add_note("C#") # write_Composition(constants.OUTPUT_DIR + fileName, composition, beat) # #compositions.append(composition) # # storage = db.Database() # storage.initDatabase() # storage.printAll() # composition = list() # # # for i in range(10): # pitch = randrange(40, 80) # duration = random() # composition.append((duration, pitch))
cagatay/Evolution-9
20d48ab1e3800461242a225b507ce757da4855b0
rttl, mingus, pybrain
diff --git a/inputs/beatles.txt b/inputs/beatles.txt new file mode 100644 index 0000000..16d1f6b --- /dev/null +++ b/inputs/beatles.txt @@ -0,0 +1,14 @@ +hardday:d=4,o=5,b=180:8c#,8d,8c#,e,p,e,8p,e,p,8e,8e,8d,8e,g,p,8e,8d,8e,c#,p,8c#,8d,8c#,e,p,e,8p,e,p,8e,8e,8d,8e,g,p,8e,8d,8e,c# +Love:d=8,o=6,b=180:d,d,d,d,4d,2p,d,d,d,d,4d,2p,d,d,d#,4e,p,4b5,2p,a5,b5,a5,g5,4g5 +Chance:d=4,o=6,b=180:e,d,c,d,g5,2p,g5,f,e,d,c,p,e,d,c,d,g5,2p,g5,f,e,d,c +Help:d=8,o=5,b=125:b,b,b,b,b,b,b,4b,4b,b,b,d6,b,a,p,4g,4p,4a#,4b,4a,4b,4b,a#,b,b,b,c6,c6,c6,c6,b,p +jude:d=8,o=5,b=180:g,e,p,e,e,g,a,d,p,p,d,e,f,c,c,c,b,g,a,g,f,4e,p,g,a,a,a,d6,c6,b,b,c6,a,4g,c,d,e,a,a,4g +Madonna:d=8,o=6,b=100:e,4e,16d5,d,16p,16c,4p,e,e,d,16a5,4c,4p,e,e,g,e,a,g,e,4c,p,c,d5,c,2p,e,4e,16d5,d,16p,16c,4p,e,e,d,16a5,4c +letitbe:d=4,o=5,b=112:16g.,8g,g,8g,a,8e,8g,g.,8c6,d.6,e6,8e6,e6,8d6,8d6,8c6,2c6,e6,8e6,f6,8e6,8e6,d.6,8e6,8d6,2c6 +do:d=4,o=6,b=180:d,d,8f,g,p,8f,8d,8d,8f,g,p,8f,8d,8d,8f,g,8p,d,e,d,c,e,p,g5,g5,a#5,g5 +you:d=8,o=6,b=180:d,e,g,4g,f#,e,p,p,d,e,g,g,f#,e,p,p,d,e,g,4g,p,4f,4p,4e +Fields:d=8,o=5,b=180:b,b,c6,b,g,d,e,a,g,f,f,g,a,d,p,2p,4f,4g,4g#,d,d6,c6,b,a,g#,a,4b,p,b,g,e,p,b,g,d,a,4g +Hand:d=8,o=6,b=180:g,a,g,p,p,f,4e,p,e,g,f,e,d,p,4e,e,e,e,e,b,p +Four:d=8,o=6,b=180:e5,d#5,e5,g5,e5,g5,a5,g5,4c,c,e,c,a5,4d,2p,b5,c,c#,d,b5,c,c#,d,b5,a#5,a5,4a5,4p,4b5,4c,4c#,4d,4e,4d#,d,c,p +Submarine:d=8,o=5,b=180:4d6,4d6,4d6,d6,e6,a,a,a,a,4a,a,a,a,a,4a,p,g,g,g,g,4g +yday:d=4,o=5,b=125:g,8f,f,p,8a,8b,8c#6,8d6,e6,8p,8f6,e6,8d6,d6,p,8d6,8d6,8c6,8a#,8a,8g,8a#,8a,8a,a,8p,g,f,8a,8g,g,8p,8d,f,8p,8a,a \ No newline at end of file diff --git a/output/A Hard Day's Night.mid b/output/A Hard Day's Night.mid new file mode 100644 index 0000000..108b57d Binary files /dev/null and b/output/A Hard Day's Night.mid differ diff --git a/output/All I've Got To Do.mid b/output/All I've Got To Do.mid new file mode 100644 index 0000000..65938a9 Binary files /dev/null and b/output/All I've Got To Do.mid differ diff --git a/output/All Together Now.mid b/output/All Together Now.mid new file mode 100644 index 0000000..d699041 Binary files /dev/null and b/output/All Together Now.mid differ diff --git a/output/And Your Bird Can Sing.mid b/output/And Your Bird Can Sing.mid new file mode 100644 index 0000000..74aeb9b Binary files /dev/null and b/output/And Your Bird Can Sing.mid differ diff --git a/src/RTTL.py b/src/RTTL.py new file mode 100644 index 0000000..a27ab94 --- /dev/null +++ b/src/RTTL.py @@ -0,0 +1,61 @@ +''' +Created on 12 Ara 2010 + +@author: melih +''' + +def parse(fileName): + file = open(fileName) + songList = list() + + + for line in file: + line = line.rstrip() + noteList = list() + parts = line.split(":") + name = parts[0] + defaults = parts[1] + notes = parts[2] + + + defaults = defaults.split(",") + defaultDuration = int(defaults[0].split("=")[1]) + defaultOctave = int(defaults[1].split("=")[1]) + bpm = int(defaults[2].split("=")[1]) + + + notes = notes.split(",") + for note in notes: + note = note.upper() + noteDuration = defaultDuration + noteOctave = defaultOctave + if note[0].isdigit(): + if note[1].isdigit(): + noteDuration = int(note[:2]) + note = note[2:] + else: + noteDuration = int(note[0]) + note = note[1:] + if note[len(note) - 1].isdigit(): + noteOctave = int(note[len(note) - 1]) + note = note[0:len(note) - 1] + + if note.endswith("."): + noteDuration = noteDuration * 1.5 + note = note[0:len(note) - 1] + if note == "P": + note = None + + noteList.append((noteDuration, note, noteOctave)) + + rttl = RTTL() + rttl.name = name + rttl.notes = noteList + rttl.bpm = bpm + songList.append(rttl) + + return songList + +class RTTL: + name = "" + \ No newline at end of file diff --git a/src/evolution9/constants.py b/src/constants.py similarity index 65% rename from src/evolution9/constants.py rename to src/constants.py index b5284f2..70f1e43 100644 --- a/src/evolution9/constants.py +++ b/src/constants.py @@ -1,8 +1,9 @@ ''' Created on Oct 10, 2010 @author: cagatay.yuksel ''' SQLITE_FILE = "../data/evolution9.db" -OUTPUT_DIR = "../output/" \ No newline at end of file +OUTPUT_DIR = "../output/" +INPUT_DIR = "../inputs/" \ No newline at end of file diff --git a/src/evolution9/evolution/storage/db.py b/src/evolution9/evolution/storage/db.py index 302a7d3..135d09b 100644 --- a/src/evolution9/evolution/storage/db.py +++ b/src/evolution9/evolution/storage/db.py @@ -1,84 +1,84 @@ ''' Created on Oct 11, 2010 @author: melih.karci ''' -from evolution9.constants import SQLITE_FILE +from constants import SQLITE_FILE import sqlite3 class Database: __connection__ = None def initDatabase(self): self.connection = sqlite3.connect(SQLITE_FILE) c = self.connection.cursor() # Create table c.execute(''' create table if not exists composers( generation integer, parent integer, gene text, status text) ''') c.close() #Commits all transactions which aren't committed and closes db connection def closeDatabase(self): self.connection.commit() self.connection.close() #Inserts new composer and returns its id def newComposer(self,generation,parent,gene,status): c=self.connection.cursor() t =(generation,parent,gene,status) c.execute(''' INSERT INTO composers VALUES (?,?,?,?) ''',t) self.connection.commit() c.execute(''' SELECT ROWID FROM composers ORDER BY ROWID DESC LIMIT 1 ''') insertedRowId = c.fetchall() c.close() return insertedRowId[0][0] #Returns composer for the given row id def getComposer(self,rowId): t = (rowId,) c=self.connection.cursor() c.execute(''' SELECT * FROM composers WHERE ROWID=? ''',t) result=c.fetchall() return result[0] #Updates status of the given row id def updateStatus(self,rowId,newStatus): t = (newStatus,rowId,) c=self.connection.cursor() c.execute(''' UPDATE composers SET status=? WHERE ROWID=? ''',t) self.connection.commit() #prints all table with column names ROWID | GENERATION | PARENT | GENE | STATUS def printAll(self): c=self.connection.cursor() c.execute('SELECT ROWID,generation,parent,gene,status FROM COMPOSERS ORDER BY ROWID DESC') for row in c: print(row) diff --git a/src/evolution9/midi/midiActions.py b/src/evolution9/midi/midiActions.py index f60066a..396594e 100644 --- a/src/evolution9/midi/midiActions.py +++ b/src/evolution9/midi/midiActions.py @@ -1,27 +1,27 @@ ''' Created on Oct 11, 2010 @author: cagatay.yuksel ''' from evolution9.midi.MidiFile3 import MIDIFile -from evolution9.constants import OUTPUT_DIR +from constants import OUTPUT_DIR def createMIDI(filename, notes): midi = MIDIFile(1) track = 0 time = 0 tempo = 200 channel = 0 volume = 100 midi.addTrackName(track, time, "track") midi.addTempo(track, time, tempo) for duration, pitch in notes: midi.addNote(track, channel, pitch, time, duration, volume) time += duration fileHandle = open(OUTPUT_DIR + filename, "wb") midi.writeFile(fileHandle) fileHandle.close() diff --git a/src/main.py b/src/main.py index 2905177..cc0b645 100644 --- a/src/main.py +++ b/src/main.py @@ -1,27 +1,78 @@ ''' Created on Oct 6, 2010 @author: cagatay.yuksel ''' from random import randrange from random import random from evolution9.midi.midiActions import createMIDI from evolution9.evolution.storage import db from pybrain.tools.shortcuts import buildNetwork +from mingus.midi.MidiFileIn import MIDI_to_Composition +from mingus.midi.MidiFileOut import write_Composition +from mingus.containers import * +import RTTL +import os +import constants -if __name__ == '__main__': - storage = db.Database() - storage.initDatabase() - storage.printAll() - composition = list() - - for i in range(10): - pitch = randrange(40, 80) - duration = random() - composition.append((duration, pitch)) +if __name__ == '__main__': + list = RTTL.parse(constants.INPUT_DIR + "beatles.txt") + + for song in list: + track = Track() + + for note in song.notes: + if not note[1]: + track.add_notes(None, note[0]) + else: + track.add_notes(Note(note[1], note[2]), note[0]) + composition = Composition() + composition.add_track(track) + composition.set_title(song.name) + write_Composition(constants.OUTPUT_DIR + song.name + ".mid", composition, song.bpm) +# defDuration = 4 +# defOctave = 5 +# beat = 180 +# +# track = Track() +# track.add_notes("C#", 8) +# track.add_notes("D", 8) +# track.add_notes("C#", 8) +# track.add_notes("E", defDuration) +# track.add_notes(None, defDuration) +# track.add_notes("E", defDuration) +# track.add_notes(None, 8) +# track.add_notes("E", defDuration) +# track.add_notes(None, defDuration) +# track.add_notes("E", 8) +# +# composition = Composition() +# composition.add_track(track) + +# write_Composition(constants.OUTPUT_DIR + "1.mid", composition, beat) +# midiFiles = os.listdir(constants.INPUT_DIR) +# compositions = list() +# +# for fileName in midiFiles: +# +# (composition, beat) = MIDI_to_Composition(constants.INPUT_DIR + fileName) +# #composition.add_note("C#") +# write_Composition(constants.OUTPUT_DIR + fileName, composition, beat) +# #compositions.append(composition) +# + +# storage = db.Database() +# storage.initDatabase() +# storage.printAll() +# composition = list() +# +# +# for i in range(10): +# pitch = randrange(40, 80) +# duration = random() +# composition.append((duration, pitch)) - createMIDI('output.mid', composition) \ No newline at end of file
cagatay/Evolution-9
abb767606c20e517f6b66fdab0accb961c520e12
PyBrain integration
diff --git a/output/output.mid b/output/output.mid index 79008e4..ac18529 100644 Binary files a/output/output.mid and b/output/output.mid differ diff --git a/src/main.py b/src/main.py index 4065184..2905177 100644 --- a/src/main.py +++ b/src/main.py @@ -1,24 +1,27 @@ ''' Created on Oct 6, 2010 @author: cagatay.yuksel ''' from random import randrange from random import random from evolution9.midi.midiActions import createMIDI from evolution9.evolution.storage import db +from pybrain.tools.shortcuts import buildNetwork + if __name__ == '__main__': storage = db.Database() storage.initDatabase() storage.printAll() composition = list() + for i in range(10): pitch = randrange(40, 80) duration = random() composition.append((duration, pitch)) createMIDI('output.mid', composition) \ No newline at end of file
cagatay/Evolution-9
279db55bdc38d891898607026e5293a19bc19632
from python 2.7 to pyhton 2.6 for scipy
diff --git a/.pydevproject b/.pydevproject index aca2a86..8076667 100644 --- a/.pydevproject +++ b/.pydevproject @@ -1,10 +1,10 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?eclipse-pydev version="1.0"?> <pydev_project> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python27</pydev_property> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python26</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.6</pydev_property> <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> <path>/Evolution-9/src</path> </pydev_pathproperty> </pydev_project>
cagatay/Evolution-9
48aaa2d8890922ab495603642f8ff15a0e2c4045
from Python 3.2 to Python 2.7
diff --git a/.pydevproject b/.pydevproject index a8c8f2d..aca2a86 100644 --- a/.pydevproject +++ b/.pydevproject @@ -1,10 +1,10 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<?eclipse-pydev version="1.0"?> - -<pydev_project> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python3</pydev_property> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 3.0</pydev_property> -<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> -<path>/Evolution-9/src</path> -</pydev_pathproperty> -</pydev_project> +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?eclipse-pydev version="1.0"?> + +<pydev_project> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python27</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property> +<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> +<path>/Evolution-9/src</path> +</pydev_pathproperty> +</pydev_project> diff --git a/data/evolution9.db b/data/evolution9.db index 721a01f..5545057 100644 Binary files a/data/evolution9.db and b/data/evolution9.db differ diff --git a/output/output.mid b/output/output.mid index 4c6a97e..79008e4 100644 Binary files a/output/output.mid and b/output/output.mid differ diff --git a/src/main.py b/src/main.py index 4f5a4c3..4065184 100644 --- a/src/main.py +++ b/src/main.py @@ -1,22 +1,24 @@ ''' Created on Oct 6, 2010 @author: cagatay.yuksel ''' from random import randrange from random import random from evolution9.midi.midiActions import createMIDI from evolution9.evolution.storage import db if __name__ == '__main__': - db.initDatabase() + storage = db.Database() + storage.initDatabase() + storage.printAll() composition = list() for i in range(10): pitch = randrange(40, 80) duration = random() composition.append((duration, pitch)) createMIDI('output.mid', composition) \ No newline at end of file
cagatay/Evolution-9
aed6c94f90ed27d8e9df480e0d446fc5ec9a434c
veritabanı metodları
diff --git a/src/evolution9/evolution/storage/storageActions.py b/src/evolution9/evolution/storage/storageActions.py index 08bb33a..0331f8a 100644 --- a/src/evolution9/evolution/storage/storageActions.py +++ b/src/evolution9/evolution/storage/storageActions.py @@ -1,6 +1,10 @@ -''' -Created on Oct 11, 2010 - -@author: cagatay.yuksel -''' - +''' +Created on Oct 11, 2010 + +@author: cagatay.yuksel +''' + +def putComposer(generation, gene, parent): + + return 0 +
cagatay/Evolution-9
dc9b1a505874f6b40d43ba1b9c688ecd36e86f1b
veritabanı metodları
diff --git a/src/evolution9/evolution/storage/db.py b/src/evolution9/evolution/storage/db.py index 95da85c..302a7d3 100644 --- a/src/evolution9/evolution/storage/db.py +++ b/src/evolution9/evolution/storage/db.py @@ -1,22 +1,84 @@ -''' -Created on Oct 11, 2010 - -@author: cagatay.yuksel -''' - -from evolution9.constants import SQLITE_FILE -import sqlite3 - -def initDatabase(): - connection = sqlite3.connect(SQLITE_FILE) - c = connection.cursor() - - # Create table - c.execute(''' - create table if not exists composers( - generation integer, - gene text, - status text) - ''') - c.close() - connection.close() +''' +Created on Oct 11, 2010 + +@author: melih.karci +''' + +from evolution9.constants import SQLITE_FILE +import sqlite3 + +class Database: + __connection__ = None + + def initDatabase(self): + self.connection = sqlite3.connect(SQLITE_FILE) + c = self.connection.cursor() + # Create table + c.execute(''' + create table if not exists composers( + generation integer, + parent integer, + gene text, + status text) + ''') + c.close() + + #Commits all transactions which aren't committed and closes db connection + def closeDatabase(self): + self.connection.commit() + self.connection.close() + + + #Inserts new composer and returns its id + def newComposer(self,generation,parent,gene,status): + c=self.connection.cursor() + t =(generation,parent,gene,status) + c.execute(''' + INSERT INTO composers VALUES (?,?,?,?) + ''',t) + self.connection.commit() + c.execute(''' + SELECT ROWID FROM composers ORDER BY ROWID DESC LIMIT 1 + ''') + insertedRowId = c.fetchall() + c.close() + return insertedRowId[0][0] + + + #Returns composer for the given row id + def getComposer(self,rowId): + t = (rowId,) + c=self.connection.cursor() + c.execute(''' + SELECT * FROM composers WHERE ROWID=? + ''',t) + result=c.fetchall() + return result[0] + + #Updates status of the given row id + def updateStatus(self,rowId,newStatus): + t = (newStatus,rowId,) + c=self.connection.cursor() + c.execute(''' + UPDATE composers SET status=? WHERE ROWID=? + ''',t) + self.connection.commit() + + #prints all table with column names ROWID | GENERATION | PARENT | GENE | STATUS + def printAll(self): + c=self.connection.cursor() + c.execute('SELECT ROWID,generation,parent,gene,status FROM COMPOSERS ORDER BY ROWID DESC') + for row in c: + print(row) + + + + + + + + + + + +
cagatay/Evolution-9
609719bf718d078fd2f9488b2c419e54387fdc93
deneme
diff --git a/src/main.py b/src/main.py index 60a98f9..4f5a4c3 100644 --- a/src/main.py +++ b/src/main.py @@ -1,22 +1,22 @@ ''' -Created on Oct 5, 2010 +Created on Oct 6, 2010 @author: cagatay.yuksel ''' from random import randrange from random import random from evolution9.midi.midiActions import createMIDI from evolution9.evolution.storage import db if __name__ == '__main__': db.initDatabase() composition = list() for i in range(10): pitch = randrange(40, 80) duration = random() composition.append((duration, pitch)) createMIDI('output.mid', composition) \ No newline at end of file
cagatay/Evolution-9
3ff8820fed6c099b8b29dbd560f34c1963a44b80
@readme
diff --git a/README.txt b/README.txt index e69de29..1e5dcc6 100644 --- a/README.txt +++ b/README.txt @@ -0,0 +1 @@ +@readme \ No newline at end of file
cagatay/Evolution-9
4160303f7fd013a26dd91915813df380498db462
sqlite
diff --git a/data/evolution9.db b/data/evolution9.db new file mode 100644 index 0000000..721a01f Binary files /dev/null and b/data/evolution9.db differ diff --git a/output/output.mid b/output/output.mid index 2663aa9..4c6a97e 100644 Binary files a/output/output.mid and b/output/output.mid differ diff --git a/src/evolution9/evolution/__init__.py b/src/evolution9/evolution/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/evolution9/evolution/storage/__init__.py b/src/evolution9/evolution/storage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/evolution9/evolution/storage/db.py b/src/evolution9/evolution/storage/db.py new file mode 100644 index 0000000..95da85c --- /dev/null +++ b/src/evolution9/evolution/storage/db.py @@ -0,0 +1,22 @@ +''' +Created on Oct 11, 2010 + +@author: cagatay.yuksel +''' + +from evolution9.constants import SQLITE_FILE +import sqlite3 + +def initDatabase(): + connection = sqlite3.connect(SQLITE_FILE) + c = connection.cursor() + + # Create table + c.execute(''' + create table if not exists composers( + generation integer, + gene text, + status text) + ''') + c.close() + connection.close() diff --git a/src/evolution9/evolution/storage/storageActions.py b/src/evolution9/evolution/storage/storageActions.py new file mode 100644 index 0000000..08bb33a --- /dev/null +++ b/src/evolution9/evolution/storage/storageActions.py @@ -0,0 +1,6 @@ +''' +Created on Oct 11, 2010 + +@author: cagatay.yuksel +''' +
cagatay/Evolution-9
316a4d19310f2ce1846ca456e4f468c1e7f5a6f2
basic db operations
diff --git a/.pydevproject b/.pydevproject index 92f334f..a8c8f2d 100644 --- a/.pydevproject +++ b/.pydevproject @@ -1,10 +1,10 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?eclipse-pydev version="1.0"?> <pydev_project> -<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python31</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python3</pydev_property> <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 3.0</pydev_property> <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> <path>/Evolution-9/src</path> </pydev_pathproperty> </pydev_project> diff --git a/src/evolution9/constants.py b/src/evolution9/constants.py index 8950afc..b5284f2 100644 --- a/src/evolution9/constants.py +++ b/src/evolution9/constants.py @@ -1,8 +1,8 @@ ''' Created on Oct 10, 2010 @author: cagatay.yuksel ''' -SQLITE_FILE = "evolution9.db" +SQLITE_FILE = "../data/evolution9.db" OUTPUT_DIR = "../output/" \ No newline at end of file diff --git a/src/main.py b/src/main.py index 7a0852e..60a98f9 100644 --- a/src/main.py +++ b/src/main.py @@ -1,17 +1,22 @@ ''' Created on Oct 5, 2010 @author: cagatay.yuksel ''' from random import randrange +from random import random from evolution9.midi.midiActions import createMIDI +from evolution9.evolution.storage import db -composition = list() +if __name__ == '__main__': + db.initDatabase() + composition = list() -for i in range(10): - pitch = randrange(40, 80) - composition.append((1, pitch)) - -createMIDI('output.mid', composition) \ No newline at end of file + for i in range(10): + pitch = randrange(40, 80) + duration = random() + composition.append((duration, pitch)) + + createMIDI('output.mid', composition) \ No newline at end of file diff --git a/src/midiutil/MidiFile3.pyc b/src/midiutil/MidiFile3.pyc deleted file mode 100644 index 6b8365c..0000000 Binary files a/src/midiutil/MidiFile3.pyc and /dev/null differ diff --git a/src/midiutil/__init__.pyc b/src/midiutil/__init__.pyc deleted file mode 100644 index 0d58a8b..0000000 Binary files a/src/midiutil/__init__.pyc and /dev/null differ
cagatay/Evolution-9
2a193a82d96c8a918067da4bc0b6654b47a9171b
added license info
diff --git a/COPYING.txt b/COPYING.txt new file mode 100644 index 0000000..8cffccc --- /dev/null +++ b/COPYING.txt @@ -0,0 +1,13 @@ + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2004 Sam Hocevar <[email protected]> + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. \ No newline at end of file diff --git a/README b/README.txt similarity index 100% rename from README rename to README.txt
cagatay/Evolution-9
a80e7b5ba20264328b93cf73255941f144deaf52
composing random midi
diff --git a/src/midiutil/__init__.py b/src/evolution9/__init__.py similarity index 100% rename from src/midiutil/__init__.py rename to src/evolution9/__init__.py diff --git a/src/evolution9/constants.py b/src/evolution9/constants.py new file mode 100644 index 0000000..8950afc --- /dev/null +++ b/src/evolution9/constants.py @@ -0,0 +1,8 @@ +''' +Created on Oct 10, 2010 + +@author: cagatay.yuksel +''' + +SQLITE_FILE = "evolution9.db" +OUTPUT_DIR = "../output/" \ No newline at end of file diff --git a/src/midiutil/MidiFile3.py b/src/evolution9/midi/MidiFile3.py similarity index 100% rename from src/midiutil/MidiFile3.py rename to src/evolution9/midi/MidiFile3.py diff --git a/src/evolution9/midi/__init__.py b/src/evolution9/midi/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/evolution9/midi/midiActions.py b/src/evolution9/midi/midiActions.py new file mode 100644 index 0000000..f60066a --- /dev/null +++ b/src/evolution9/midi/midiActions.py @@ -0,0 +1,27 @@ +''' +Created on Oct 11, 2010 + +@author: cagatay.yuksel +''' + +from evolution9.midi.MidiFile3 import MIDIFile +from evolution9.constants import OUTPUT_DIR + +def createMIDI(filename, notes): + midi = MIDIFile(1) + track = 0 + time = 0 + tempo = 200 + channel = 0 + volume = 100 + + midi.addTrackName(track, time, "track") + midi.addTempo(track, time, tempo) + + for duration, pitch in notes: + midi.addNote(track, channel, pitch, time, duration, volume) + time += duration + + fileHandle = open(OUTPUT_DIR + filename, "wb") + midi.writeFile(fileHandle) + fileHandle.close() diff --git a/src/main.py b/src/main.py index 0863ba1..7a0852e 100644 --- a/src/main.py +++ b/src/main.py @@ -1,38 +1,17 @@ -#=============================================================================== -# Created on Oct 5, 2010 -# -# @author: cagatay -#=============================================================================== +''' +Created on Oct 5, 2010 + +@author: cagatay.yuksel +''' -#Import the library -from midiutil.MidiFile3 import MIDIFile +from random import randrange -# Create the MIDIFile Object with 1 track -MyMIDI = MIDIFile(1) +from evolution9.midi.midiActions import createMIDI -# Tracks are numbered from zero. Times are measured in beats. -track = 0 -time = 0 +composition = list() -# Add track name and tempo. -MyMIDI.addTrackName(track, time, "Sample Track") -MyMIDI.addTempo(track, time, 120) - -# Add a note. addNote expects the following information: -track = 0 -channel = 0 -pitch = 60 -time = 0 -duration = 1 -volume = 100 - -# Now add the note. -MyMIDI.addNote(track, channel, pitch, time, duration, volume) -MyMIDI.addNote(track, channel, pitch, time+1, duration, volume) -MyMIDI.addNote(track, channel, 70, time+2, duration, volume) -MyMIDI.addNote(track, channel, 80, time+3, duration, volume) -# And write it to disk. -binfile = open("../output/output.mid", 'wb') -MyMIDI.writeFile(binfile) -binfile.close() +for i in range(10): + pitch = randrange(40, 80) + composition.append((1, pitch)) +createMIDI('output.mid', composition) \ No newline at end of file
cagatay/Evolution-9
04a47cf71277d4d648b9fc32e2c0934a78940b5f
plays midi
diff --git a/.project b/.project new file mode 100644 index 0000000..2507761 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>Evolution-9</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.python.pydev.PyDevBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.python.pydev.pythonNature</nature> + </natures> +</projectDescription> diff --git a/.pydevproject b/.pydevproject new file mode 100644 index 0000000..92f334f --- /dev/null +++ b/.pydevproject @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?eclipse-pydev version="1.0"?> + +<pydev_project> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python31</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 3.0</pydev_property> +<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> +<path>/Evolution-9/src</path> +</pydev_pathproperty> +</pydev_project> diff --git a/output/output.mid b/output/output.mid new file mode 100644 index 0000000..2663aa9 Binary files /dev/null and b/output/output.mid differ diff --git a/src/main.py b/src/main.py index cbd6351..0863ba1 100644 --- a/src/main.py +++ b/src/main.py @@ -1,5 +1,38 @@ #=============================================================================== # Created on Oct 5, 2010 # # @author: cagatay -#=============================================================================== \ No newline at end of file +#=============================================================================== + +#Import the library +from midiutil.MidiFile3 import MIDIFile + +# Create the MIDIFile Object with 1 track +MyMIDI = MIDIFile(1) + +# Tracks are numbered from zero. Times are measured in beats. +track = 0 +time = 0 + +# Add track name and tempo. +MyMIDI.addTrackName(track, time, "Sample Track") +MyMIDI.addTempo(track, time, 120) + +# Add a note. addNote expects the following information: +track = 0 +channel = 0 +pitch = 60 +time = 0 +duration = 1 +volume = 100 + +# Now add the note. +MyMIDI.addNote(track, channel, pitch, time, duration, volume) +MyMIDI.addNote(track, channel, pitch, time+1, duration, volume) +MyMIDI.addNote(track, channel, 70, time+2, duration, volume) +MyMIDI.addNote(track, channel, 80, time+3, duration, volume) +# And write it to disk. +binfile = open("../output/output.mid", 'wb') +MyMIDI.writeFile(binfile) +binfile.close() + diff --git a/src/midiutil/MidiFile3.py b/src/midiutil/MidiFile3.py new file mode 100644 index 0000000..31dcf24 --- /dev/null +++ b/src/midiutil/MidiFile3.py @@ -0,0 +1,1007 @@ +#----------------------------------------------------------------------------- +# Name: MidiFile.py +# Purpose: MIDI file manipulation utilities +# +# Author: Mark Conway Wirt <emergentmusics) at (gmail . com> +# +# Created: 2008/04/17 +# Copyright: (c) 2009 Mark Conway Wirt +# License: Please see License.txt for the terms under which this +# software is distributed. +#----------------------------------------------------------------------------- + +import sys, math, struct + +# TICKSPERBEAT is the number of "ticks" (time measurement in the MIDI file) that +# corresponds to one beat. This number is somewhat arbitrary, but should be chosen +# to provide adequate temporal resolution. + +TICKSPERBEAT = 128 + +controllerEventTypes = { + 'pan' : 0x0a + } +class MIDIEvent: + ''' + The class to contain the MIDI Event (placed on MIDIEventList. + ''' + def __init__(self): + self.type='unknown' + self.time=0 + self.ord = 0 + + def __lt__(self, other): + ''' Sorting function for events.''' + if self.time < other.time: + return True + elif self.time > other.time: + return False + else: + if self.ord < other.ord: + return True + elif self.ord > other.ord: + return False + else: + return False + + def __cmp__(self, other): + ''' Sorting function for events.''' + if self.time < other.time: + return -1 + elif self.time > other.time: + return 1 + else: + if self.ord < other.ord: + return -1 + elif self.ord > other.ord: + return 1 + else: + return 0 + +class GenericEvent(): + '''The event class from which specific events are derived + ''' + def __init__(self,time): + self.time = time + self.type = 'Unknown' + + + + def __eq__(self, other): + ''' + Equality operator for Generic Events and derived classes. + + In the processing of the event list, we have need to remove duplicates. To do this + we rely on the fact that the classes are hashable, and must therefore have an + equality operator (__hash__() and __eq__() must both be defined). + + This is the most embarrassing portion of the code, and anyone who knows about OO + programming would find this almost unbelievable. Here we have a base class that + knows specifics about derived classes, thus breaking the very spirit of + OO programming. + + I suppose I should go back and restructure the code, perhaps removing the derived + classes altogether. At some point perhaps I will. + ''' + if self.time != other.time or self.type != other.type: + return False + + # What follows is code that encodes the concept of equality for each derived + # class. Believe it f you dare. + + if self.type == 'note': + if self.pitch != other.pitch or self.channel != other.channel: + return False + if self.type == 'tempo': + if self.tempo != other.tempo: + return False + if self.type == 'programChange': + if self.programNumber != other.programNumber or self.channel != other.channel: + return False + if self.type == 'trackName': + if self.trackName != other.trackName: + return False + if self.type == 'controllerEvent': + if self.parameter1 != other.parameter1 or \ + self.parameter2 != other.parameter2 or \ + self.channel != other.channel or \ + self.eventType != other.eventType: + return False + + if self.type == 'SysEx': + if self.manID != other.manID: + return False + + if self.type == 'UniversalSysEx': + if self.code != other.code or\ + self.subcode != other.subcode or \ + self.sysExChannel != other.sysExChannel: + return False + + return True + + def __hash__(self): + ''' + Return a hash code for the object. + + This is needed for the removal of duplicate objects from the event list. The only + real requirement for the algorithm is that the hash of equal objects must be equal. + There is probably great opportunity for improvements in the hashing function. + ''' + # Robert Jenkin's 32 bit hash. + a = int(self.time) + a = (a+0x7ed55d16) + (a<<12) + a = (a^0xc761c23c) ^ (a>>19) + a = (a+0x165667b1) + (a<<5) + a = (a+0xd3a2646c) ^ (a<<9) + a = (a+0xfd7046c5) + (a<<3) + a = (a^0xb55a4f09) ^ (a>>16) + return a + +class MIDITrack: + '''A class that encapsulates a MIDI track + ''' + # Nested class definitions. + + class note(GenericEvent): + '''A class that encapsulates a note + ''' + def __init__(self,channel, pitch,time,duration,volume): + + GenericEvent.__init__(self,time) + self.pitch = pitch + self.duration = duration + self.volume = volume + self.type = 'note' + self.channel = channel + + def compare(self, other): + '''Compare two notes for equality. + ''' + if self.pitch == other.pitch and \ + self.time == other.time and \ + self.duration == other.duration and \ + self.volume == other.volume and \ + self.type == other.type and \ + self.channel == other.channel: + return True + else: + return False + + + class tempo(GenericEvent): + '''A class that encapsulates a tempo meta-event + ''' + def __init__(self,time,tempo): + + GenericEvent.__init__(self,time) + self.type = 'tempo' + self.tempo = int(60000000 / tempo) + + class programChange(GenericEvent): + '''A class that encapsulates a program change event. + ''' + + def __init__(self, channel, time, programNumber): + GenericEvent.__init__(self, time,) + self.type = 'programChange' + self.programNumber = programNumber + self.channel = channel + + class SysExEvent(GenericEvent): + '''A class that encapsulates a System Exclusive event. + ''' + + def __init__(self, time, manID, payload): + GenericEvent.__init__(self, time,) + self.type = 'SysEx' + self.manID = manID + self.payload = payload + + class UniversalSysExEvent(GenericEvent): + '''A class that encapsulates a Universal System Exclusive event. + ''' + + def __init__(self, time, realTime, sysExChannel, code, subcode, payload): + GenericEvent.__init__(self, time,) + self.type = 'UniversalSysEx' + self.realTime = realTime + self.sysExChannel = sysExChannel + self.code = code + self.subcode = subcode + self.payload = payload + + class ControllerEvent(GenericEvent): + '''A class that encapsulates a program change event. + ''' + + def __init__(self, channel, time, eventType, parameter1,): + GenericEvent.__init__(self, time,) + self.type = 'controllerEvent' + self.parameter1 = parameter1 + self.channel = channel + self.eventType = eventType + + class trackName(GenericEvent): + '''A class that encapsulates a program change event. + ''' + + def __init__(self, time, trackName): + GenericEvent.__init__(self, time,) + self.type = 'trackName' + self.trackName = trackName + + + def __init__(self, removeDuplicates, deinterleave): + '''Initialize the MIDITrack object. + ''' + self.headerString = struct.pack('cccc','M','T','r','k') + self.dataLength = 0 # Is calculated after the data is in place + self.MIDIdata = b"" + self.closed = False + self.eventList = [] + self.MIDIEventList = [] + self.remdep = removeDuplicates + self.deinterleave = deinterleave + + def addNoteByNumber(self,channel, pitch,time,duration,volume): + '''Add a note by chromatic MIDI number + ''' + self.eventList.append(MIDITrack.note(channel, pitch,time,duration,volume)) + + def addControllerEvent(self,channel,time,eventType, paramerter1): + ''' + Add a controller event. + ''' + + self.eventList.append(MIDITrack.ControllerEvent(channel,time,eventType, \ + paramerter1)) + + def addTempo(self,time,tempo): + ''' + Add a tempo change (or set) event. + ''' + self.eventList.append(MIDITrack.tempo(time,tempo)) + + def addSysEx(self,time,manID, payload): + ''' + Add a SysEx event. + ''' + self.eventList.append(MIDITrack.SysExEvent(time, manID, payload)) + + def addUniversalSysEx(self,time,code, subcode, payload, sysExChannel=0x7F, \ + realTime=False): + ''' + Add a Universal SysEx event. + ''' + self.eventList.append(MIDITrack.UniversalSysExEvent(time, realTime, \ + sysExChannel, code, subcode, payload)) + + def addProgramChange(self,channel, time, program): + ''' + Add a program change event. + ''' + self.eventList.append(MIDITrack.programChange(channel, time, program)) + + def addTrackName(self,time,trackName): + ''' + Add a track name event. + ''' + self.eventList.append(MIDITrack.trackName(time,trackName)) + + def changeNoteTuning(self, tunings, sysExChannel=0x7F, realTime=False, \ + tuningProgam=0): + '''Change the tuning of MIDI notes + ''' + payload = struct.pack('>B', tuningProgam) + payload = payload + struct.pack('>B', len(tunings)) + for (noteNumber, frequency) in tunings: + payload = payload + struct.pack('>B', noteNumber) + MIDIFreqency = frequencyTransform(frequency) + for byte in MIDIFreqency: + payload = payload + struct.pack('>B', byte) + + self.eventList.append(MIDITrack.UniversalSysExEvent(0, realTime, sysExChannel,\ + 8, 2, payload)) + + def processEventList(self): + ''' + Process the event list, creating a MIDIEventList + + For each item in the event list, one or more events in the MIDIEvent + list are created. + ''' + + # Loop over all items in the eventList + + for thing in self.eventList: + if thing.type == 'note': + event = MIDIEvent() + event.type = "NoteOn" + event.time = thing.time * TICKSPERBEAT + event.pitch = thing.pitch + event.volume = thing.volume + event.channel = thing.channel + event.ord = 3 + self.MIDIEventList.append(event) + + event = MIDIEvent() + event.type = "NoteOff" + event.time = (thing.time + thing.duration) * TICKSPERBEAT + event.pitch = thing.pitch + event.volume = thing.volume + event.channel = thing.channel + event.ord = 2 + self.MIDIEventList.append(event) + + elif thing.type == 'tempo': + event = MIDIEvent() + event.type = "Tempo" + event.time = thing.time * TICKSPERBEAT + event.tempo = thing.tempo + event.ord = 3 + self.MIDIEventList.append(event) + + elif thing.type == 'programChange': + event = MIDIEvent() + event.type = "ProgramChange" + event.time = thing.time * TICKSPERBEAT + event.programNumber = thing.programNumber + event.channel = thing.channel + event.ord = 1 + self.MIDIEventList.append(event) + + elif thing.type == 'trackName': + event = MIDIEvent() + event.type = "TrackName" + event.time = thing.time * TICKSPERBEAT + event.trackName = thing.trackName + event.ord = 0 + self.MIDIEventList.append(event) + + elif thing.type == 'controllerEvent': + event = MIDIEvent() + event.type = "ControllerEvent" + event.time = thing.time * TICKSPERBEAT + event.eventType = thing.eventType + event.channel = thing.channel + event.paramerter1 = thing.parameter1 + event.ord = 1 + self.MIDIEventList.append(event) + + elif thing.type == 'SysEx': + event = MIDIEvent() + event.type = "SysEx" + event.time = thing.time * TICKSPERBEAT + event.manID = thing.manID + event.payload = thing.payload + event.ord = 1 + self.MIDIEventList.append(event) + + elif thing.type == 'UniversalSysEx': + event = MIDIEvent() + event.type = "UniversalSysEx" + event.realTime = thing.realTime + event.sysExChannel = thing.sysExChannel + event.time = thing.time * TICKSPERBEAT + event.code = thing.code + event.subcode = thing.subcode + event.payload = thing.payload + event.ord = 1 + self.MIDIEventList.append(event) + + else: + print ("Error in MIDITrack: Unknown event type") + sys.exit(2) + + # Assumptions in the code expect the list to be time-sorted. + # self.MIDIEventList.sort(lambda x, y: x.time - y.time) + + self.MIDIEventList.sort(key=lambda x: (x.time)) + + if self.deinterleave: + self.deInterleaveNotes() + + def removeDuplicates(self): + ''' + Remove duplicates from the eventList. + + This function will remove duplicates from the eventList. This is necessary + because we the MIDI event stream can become confused otherwise. + ''' + + # For this algorithm to work, the events in the eventList must be hashable + # (that is, they must have a __hash__() and __eq__() function defined). + + tempDict = {} + for item in self.eventList: + tempDict[item] = 1 + + self.eventList = list(tempDict.keys()) + + # Sort on type, them on time. Necessary because keys() has no requirement to return + # things in any order. + + self.eventList.sort(key=lambda x: (x.type)) + self.eventList.sort(key=lambda x: (x.time)) #A bit of a hack. + + def closeTrack(self): + '''Called to close a track before writing + + This function should be called to "close a track," that is to + prepare the actual data stream for writing. Duplicate events are + removed from the eventList, and the MIDIEventList is created. + + Called by the parent MIDIFile object. + ''' + + if self.closed == True: + return + self.closed = True + + if self.remdep: + self.removeDuplicates() + + + self.processEventList() + + def writeMIDIStream(self): + ''' + Write the meta data and note data to the packed MIDI stream. + ''' + + #Process the events in the eventList + + self.writeEventsToStream() + + # Write MIDI close event. + + self.MIDIdata = self.MIDIdata + struct.pack('BBBB',0x00,0xFF, \ + 0x2F,0x00) + + # Calculate the entire length of the data and write to the header + + self.dataLength = struct.pack('>L',len(self.MIDIdata)) + + def writeEventsToStream(self): + ''' + Write the events in MIDIEvents to the MIDI stream. + ''' + + for event in self.MIDIEventList: + if event.type == "NoteOn": + code = 0x9 << 4 | event.channel + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B',code) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.pitch) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.volume) + elif event.type == "NoteOff": + code = 0x8 << 4 | event.channel + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B',code) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.pitch) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.volume) + elif event.type == "Tempo": + code = 0xFF + subcode = 0x51 + fourbite = struct.pack('>L', event.tempo) + threebite = fourbite[1:4] # Just discard the MSB + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B',code) + self.MIDIdata = self.MIDIdata + struct.pack('>B',subcode) + self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x03) # Data length: 3 + self.MIDIdata = self.MIDIdata + threebite + elif event.type == 'ProgramChange': + code = 0xC << 4 | event.channel + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B',code) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.programNumber) + elif event.type == 'TrackName': + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('B',0xFF) # Meta-event + self.MIDIdata = self.MIDIdata + struct.pack('B',0X03) # Event Type + dataLength = len(event.trackName) + dataLenghtVar = writeVarLength(dataLength) + for i in range(0,len(dataLenghtVar)): + self.MIDIdata = self.MIDIdata + struct.pack("b",dataLenghtVar[i]) + self.MIDIdata = self.MIDIdata + event.trackName.encode() + elif event.type == "ControllerEvent": + code = 0xB << 4 | event.channel + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B',code) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.eventType) + self.MIDIdata = self.MIDIdata + struct.pack('>B',event.paramerter1) + elif event.type == "SysEx": + code = 0xF0 + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B', code) + + payloadLength = writeVarLength(len(event.payload)+2) + for lenByte in payloadLength: + self.MIDIdata = self.MIDIdata + struct.pack('>B',lenByte) + + self.MIDIdata = self.MIDIdata + struct.pack('>B', event.manID) + self.MIDIdata = self.MIDIdata + event.payload + self.MIDIdata = self.MIDIdata + struct.pack('>B',0xF7) + elif event.type == "UniversalSysEx": + code = 0xF0 + varTime = writeVarLength(event.time) + for timeByte in varTime: + self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) + self.MIDIdata = self.MIDIdata + struct.pack('>B', code) + + # Do we need to add a length? + payloadLength = writeVarLength(len(event.payload)+5) + for lenByte in payloadLength: + self.MIDIdata = self.MIDIdata + struct.pack('>B',lenByte) + + if event.realTime : + self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x7F) + else: + self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x7E) + + self.MIDIdata = self.MIDIdata + struct.pack('>B', event.sysExChannel) + self.MIDIdata = self.MIDIdata + struct.pack('>B', event.code) + self.MIDIdata = self.MIDIdata + struct.pack('>B', event.subcode) + self.MIDIdata = self.MIDIdata + event.payload + self.MIDIdata = self.MIDIdata + struct.pack('>B',0xF7) + + def deInterleaveNotes(self): + '''Correct Interleaved notes. + + Because we are writing multiple notes in no particular order, we + can have notes which are interleaved with respect to their start + and stop times. This method will correct that. It expects that the + MIDIEventList has been time-ordered. + ''' + + tempEventList = [] + stack = {} + + for event in self.MIDIEventList: + + if event.type == 'NoteOn': + if str(event.pitch)+str(event.channel) in stack: + stack[str(event.pitch)+str(event.channel)].append(event.time) + else: + stack[str(event.pitch)+str(event.channel)] = [event.time] + tempEventList.append(event) + elif event.type == 'NoteOff': + if len(stack[str(event.pitch)+str(event.channel)]) > 1: + event.time = stack[str(event.pitch)+str(event.channel)].pop() + tempEventList.append(event) + else: + stack[str(event.pitch)+str(event.channel)].pop() + tempEventList.append(event) + else: + tempEventList.append(event) + + self.MIDIEventList = tempEventList + + # A little trickery here. We want to make sure that NoteOff events appear + # before NoteOn events, so we'll do two sorts -- on on type, one on time. + # This may have to be revisited, as it makes assumptions about how + # the internal sort works, and is in essence creating a sort on a primary + # and secondary key. + + self.MIDIEventList.sort(key=lambda x: (x.type)) + self.MIDIEventList.sort(key=lambda x: (x.time)) + + def adjustTime(self,origin): + ''' + Adjust Times to be relative, and zero-origined + ''' + + if len(self.MIDIEventList) == 0: + return + tempEventList = [] + + runningTime = 0 + + for event in self.MIDIEventList: + adjustedTime = event.time - origin + event.time = adjustedTime - runningTime + runningTime = adjustedTime + tempEventList.append(event) + + self.MIDIEventList = tempEventList + + def writeTrack(self,fileHandle): + ''' + Write track to disk. + ''' + + if not self.closed: + self.closeTrack() + + fileHandle.write(self.headerString) + fileHandle.write(self.dataLength) + fileHandle.write(self.MIDIdata) + + +class MIDIHeader: + ''' + Class to encapsulate the MIDI header structure. + + This class encapsulates a MIDI header structure. It isn't used for much, + but it will create the appropriately packed identifier string that all + MIDI files should contain. It is used by the MIDIFile class to create a + complete and well formed MIDI pattern. + + ''' + def __init__(self,numTracks): + ''' Initialize the data structures + ''' + self.headerString = struct.pack('cccc','M','T','h','d') + self.headerSize = struct.pack('>L',6) + # Format 1 = multi-track file + self.format = struct.pack('>H',1) + self.numTracks = struct.pack('>H',numTracks) + self.ticksPerBeat = struct.pack('>H',TICKSPERBEAT) + + + def writeFile(self,fileHandle): + fileHandle.write(self.headerString) + fileHandle.write(self.headerSize) + fileHandle.write(self.format) + fileHandle.write(self.numTracks) + fileHandle.write(self.ticksPerBeat) + +class MIDIFile: + '''Class that represents a full, well-formed MIDI pattern. + + This is a container object that contains a header, one or more tracks, + and the data associated with a proper and well-formed MIDI pattern. + + Calling: + + MyMIDI = MidiFile(tracks, removeDuplicates=True, deinterleave=True) + + normally + + MyMIDI = MidiFile(tracks) + + Arguments: + + tracks: The number of tracks this object contains + + removeDuplicates: If true (the default), the software will remove duplicate + events which have been added. For example, two notes at the same channel, + time, pitch, and duration would be considered duplicate. + + deinterleave: If True (the default), overlapping notes (same pitch, same + channel) will be modified so that they do not overlap. Otherwise the sequencing + software will need to figure out how to interpret NoteOff events upon playback. + ''' + + def __init__(self, numTracks, removeDuplicates=True, deinterleave=True): + ''' + Initialize the class + ''' + self.header = MIDIHeader(numTracks) + + self.tracks = list() + self.numTracks = numTracks + self.closed = False + + for i in range(0,numTracks): + self.tracks.append(MIDITrack(removeDuplicates, deinterleave)) + + + # Public Functions. These (for the most part) wrap the MIDITrack functions, where most + # Processing takes place. + + def addNote(self,track, channel, pitch,time,duration,volume): + """ + Add notes to the MIDIFile object + + Use: + MyMIDI.addNotes(track,channel,pitch,time, duration, volume) + + Arguments: + track: The track to which the note is added. + channel: the MIDI channel to assign to the note. [Integer, 0-15] + pitch: the MIDI pitch number [Integer, 0-127]. + time: the time (in beats) at which the note sounds [Float]. + duration: the duration of the note (in beats) [Float]. + volume: the volume (velocity) of the note. [Integer, 0-127]. + """ + self.tracks[track].addNoteByNumber(channel, pitch, time, duration, volume) + + def addTrackName(self,track, time,trackName): + """ + Add a track name to a MIDI track. + + Use: + MyMIDI.addTrackName(track,time,trackName) + + Argument: + track: The track to which the name is added. [Integer, 0-127]. + time: The time at which the track name is added, in beats [Float]. + trackName: The track name. [String]. + """ + self.tracks[track].addTrackName(time,trackName) + + def addTempo(self,track, time,tempo): + """ + Add a tempo event. + + Use: + MyMIDI.addTempo(track, time, tempo) + + Arguments: + track: The track to which the event is added. [Integer, 0-127]. + time: The time at which the event is added, in beats. [Float]. + tempo: The tempo, in Beats per Minute. [Integer] + """ + self.tracks[track].addTempo(time,tempo) + + def addProgramChange(self,track, channel, time, program): + """ + Add a MIDI program change event. + + Use: + MyMIDI.addProgramChange(track,channel, time, program) + + Arguments: + track: The track to which the event is added. [Integer, 0-127]. + channel: The channel the event is assigned to. [Integer, 0-15]. + time: The time at which the event is added, in beats. [Float]. + program: the program number. [Integer, 0-127]. + """ + self.tracks[track].addProgramChange(channel, time, program) + + def addControllerEvent(self,track, channel,time,eventType, paramerter1): + """ + Add a MIDI controller event. + + Use: + MyMIDI.addControllerEvent(track, channel, time, eventType, parameter1) + + Arguments: + track: The track to which the event is added. [Integer, 0-127]. + channel: The channel the event is assigned to. [Integer, 0-15]. + time: The time at which the event is added, in beats. [Float]. + eventType: the controller event type. + parameter1: The event's parameter. The meaning of which varies by event type. + """ + self.tracks[track].addControllerEvent(channel,time,eventType, paramerter1) + + def changeNoteTuning(self, track, tunings, sysExChannel=0x7F, \ + realTime=False, tuningProgam=0): + """ + Change a note's tuning using SysEx change tuning program. + + Use: + MyMIDI.changeNoteTuning(track,[tunings],realTime=False, tuningProgram=0) + + Arguments: + track: The track to which the event is added. [Integer, 0-127]. + tunings: A list of tuples in the form (pitchNumber, frequency). + [[(Integer,Float]] + realTime: Boolean which sets the real-time flag. Defaults to false. + sysExChannel: do note use (see below). + tuningProgram: Tuning program to assign. Defaults to zero. [Integer, 0-127] + + In general the sysExChannel should not be changed (parameter will be depreciated). + + Also note that many software packages and hardware packages do not implement + this standard! + """ + self.tracks[track].changeNoteTuning(tunings, sysExChannel, realTime,\ + tuningProgam) + + def writeFile(self,fileHandle): + ''' + Write the MIDI File. + + Use: + MyMIDI.writeFile(filehandle) + + Arguments: + filehandle: a file handle that has been opened for binary writing. + ''' + + self.header.writeFile(fileHandle) + + #Close the tracks and have them create the MIDI event data structures. + self.close() + + #Write the MIDI Events to file. + for i in range(0,self.numTracks): + self.tracks[i].writeTrack(fileHandle) + + def addSysEx(self,track, time, manID, payload): + """ + Add a SysEx event + + Use: + MyMIDI.addSysEx(track,time,ID,payload) + + Arguments: + track: The track to which the event is added. [Integer, 0-127]. + time: The time at which the event is added, in beats. [Float]. + ID: The SysEx ID number + payload: the event payload. + + Note: This is a low-level MIDI function, so care must be used in + constructing the payload. It is recommended that higher-level helper + functions be written to wrap this function and construct the payload if + a developer finds him or herself using the function heavily. + """ + self.tracks[track].addSysEx(time,manID, payload) + + def addUniversalSysEx(self,track, time,code, subcode, payload, \ + sysExChannel=0x7F, realTime=False): + """ + Add a Universal SysEx event. + + Use: + MyMIDI.addUniversalSysEx(track, time, code, subcode, payload,\ + sysExChannel=0x7f, realTime=False) + + Arguments: + track: The track to which the event is added. [Integer, 0-127]. + time: The time at which the event is added, in beats. [Float]. + code: The even code. [Integer] + subcode The event sub-code [Integer] + payload: The event payload. [Binary string] + sysExChannel: The SysEx channel. + realTime: Sets the real-time flag. Defaults to zero. + + Note: This is a low-level MIDI function, so care must be used in + constructing the payload. It is recommended that higher-level helper + functions be written to wrap this function and construct the payload if + a developer finds him or herself using the function heavily. As an example + of such a helper function, see the changeNoteTuning function, both here and + in MIDITrack. + """ + + self.tracks[track].addUniversalSysEx(time,code, subcode, payload, sysExChannel,\ + realTime) + + def shiftTracks(self, offset=0): + """Shift tracks to be zero-origined, or origined at offset. + + Note that the shifting of the time in the tracks uses the MIDIEventList -- in other + words it is assumed to be called in the stage where the MIDIEventList has been + created. This function, however, it meant to operate on the eventList itself. + """ + origin = 1000000 # A little silly, but we'll assume big enough + + for track in self.tracks: + if len(track.eventList) > 0: + for event in track.eventList: + if event.time < origin: + origin = event.time + + for track in self.tracks: + tempEventList = [] + #runningTime = 0 + + for event in track.eventList: + adjustedTime = event.time - origin + #event.time = adjustedTime - runningTime + offset + event.time = adjustedTime + offset + #runningTime = adjustedTime + tempEventList.append(event) + + track.eventList = tempEventList + + #End Public Functions ######################## + + def close(self): + '''Close the MIDIFile for further writing. + + To close the File for events, we must close the tracks, adjust the time to be + zero-origined, and have the tracks write to their MIDI Stream data structure. + ''' + + if self.closed == True: + return + + for i in range(0,self.numTracks): + self.tracks[i].closeTrack() + # We want things like program changes to come before notes when they are at the + # same time, so we sort the MIDI events by their ordinality + self.tracks[i].MIDIEventList.sort() + + origin = self.findOrigin() + + for i in range(0,self.numTracks): + self.tracks[i].adjustTime(origin) + self.tracks[i].writeMIDIStream() + + self.closed = True + + + def findOrigin(self): + '''Find the earliest time in the file's tracks.append. + ''' + origin = 1000000 # A little silly, but we'll assume big enough + + # Note: This code assumes that the MIDIEventList has been sorted, so this should be insured + # before it is called. It is probably a poor design to do this. + # TODO: -- Consider making this less efficient but more robust by not assuming the list to be sorted. + + for track in self.tracks: + if len(track.MIDIEventList) > 0: + if track.MIDIEventList[0].time < origin: + origin = track.MIDIEventList[0].time + + + return origin + +def writeVarLength(i): + '''Accept an input, and write a MIDI-compatible variable length stream + + The MIDI format is a little strange, and makes use of so-called variable + length quantities. These quantities are a stream of bytes. If the most + significant bit is 1, then more bytes follow. If it is zero, then the + byte in question is the last in the stream + ''' + input = int(i) + output = [0,0,0,0] + reversed = [0,0,0,0] + count = 0 + result = input & 0x7F + output[count] = result + count = count + 1 + input = input >> 7 + while input > 0: + result = input & 0x7F + result = result | 0x80 + output[count] = result + count = count + 1 + input = input >> 7 + + reversed[0] = output[3] + reversed[1] = output[2] + reversed[2] = output[1] + reversed[3] = output[0] + return reversed[4-count:4] + +def frequencyTransform(freq): + '''Returns a three-byte transform of a frequencyTransform + ''' + resolution = 16384 + freq = float(freq) + dollars = 69 + 12 * math.log(freq/(float(440)), 2) + firstByte = int(dollars) + lowerFreq = 440 * pow(2.0, ((float(firstByte) - 69.0)/12.0)) + if freq != lowerFreq: + centDif = 1200 * math.log( (freq/lowerFreq), 2) + else: + centDif = 0 + cents = round(centDif/100 * resolution) # round? + secondByte = min([int(cents)>>7, 0x7F]) + thirdByte = cents - (secondByte << 7) + thirdByte = min([thirdByte, 0x7f]) + if thirdByte == 0x7f and secondByte == 0x7F and firstByte == 0x7F: + thirdByte = 0x7e + + thirdByte = int(thirdByte) + return [firstByte, secondByte, thirdByte] + +def returnFrequency(freqBytes): + '''The reverse of frequencyTransform. Given a byte stream, return a frequency. + ''' + resolution = 16384.0 + baseFrequency = 440 * pow(2.0, (float(freqBytes[0]-69.0)/12.0)) + frac = (float((int(freqBytes[1]) << 7) + int(freqBytes[2])) * 100.0) / resolution + frequency = baseFrequency * pow(2.0, frac/1200.0) + return frequency diff --git a/src/midiutil/MidiFile3.pyc b/src/midiutil/MidiFile3.pyc new file mode 100644 index 0000000..6b8365c Binary files /dev/null and b/src/midiutil/MidiFile3.pyc differ diff --git a/src/midiutil/__init__.py b/src/midiutil/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/midiutil/__init__.pyc b/src/midiutil/__init__.pyc new file mode 100644 index 0000000..0d58a8b Binary files /dev/null and b/src/midiutil/__init__.pyc differ
jeremybaumont/Oracle-puppet-module
5155dc16a8a44c0e38b65b6f4caea103786629b0
Add passwordless for dbwatch monitoring
diff --git a/modules/oracle/files/users/oracle/.ssh/authorized_keys b/modules/oracle/files/users/oracle/.ssh/authorized_keys index a9f2bef..dce1d96 100644 --- a/modules/oracle/files/users/oracle/.ssh/authorized_keys +++ b/modules/oracle/files/users/oracle/.ssh/authorized_keys @@ -1 +1,2 @@ ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1YrAHPlpMxJiRNZurbMfrbLtMmSS8RpnP1hmTCO6ac7MDqK/MEkkrcqfLOvejLViWpRKyEk6ifZDA6kzmyG8PXdL2FT24AtswWPV6vcQjroejXSj8h2q/7GB7dwyDj5MF7q8SfUg3EDx1VoaXf1hs8WIHV1Esd3a4rIZGu3KGQPQg3uyweoeEn/iy6a4b+sBMH3LglmMLd2rFhroZY3J2606IWM3bcJl7wEBmc7Z7rr3jrSn0YpgzOeXIDhnK+nJ5YFp8lNTxEvlkdhlpLH+uAGxS4LVQaTPvwXB3JQrRG3jx/VO0jdPE/gG5G1dl0R7FdlPBJh2frKXukBZJaxpJQ== [email protected] +ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEArf0wXiV/ASzt2Vz7cbAvIBLM/qu9BjtZRIkTLVpu5TDKrYs1HPAZ6MeK8g2T2bNQcw/E+gnu0PALrfXwrruzO+WL/MGRlN9VIS4iFv5qgLQSeo1jZh8LbKwgTdV0CBt1XWfxSqm1d0MF+O+iUXxUVm5dpE8SInjSIOO77TjnSe8= [email protected]
jeremybaumont/Oracle-puppet-module
02f03e98e14aa2505c0dc4853f87b11933a5cac1
Fix bug 000124 add PERL5LIB to unix env vars
diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index 169e54a..576589e 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,81 +1,82 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } # Display main environment variables inforacle() { log "INFO" "ORACLE_SID=${ORACLE_SID}" log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" log "INFO" "ORACLE_HOME=${ORACLE_HOME}" } # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> IMFLOG=/logs/oracle NLS_LANG=American_America.UTF8 +PERL5LIB=/opt/IMS/lib:. -export IMFLOG ORACLE_BASE NLS_LANG ORACLE_VERSION ORACLE_HOME ORACLE_SID +export PERL5LIB IMFLOG ORACLE_BASE NLS_LANG ORACLE_VERSION ORACLE_HOME ORACLE_SID # update lib path and command path export PATH=/opt/IMF/current/bin:$ORACLE_BASE/bin:$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$HOME/bin:$PATH export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH # oracle alias to speed up productivity alias rm='rm -i' alias sid='env|grep ORACLE_SID' alias i='inforacle' # display oracle main environment at login inforacle # set up X display and term for screen # kind of magic here but the silent installer need # to make an x connection in order to load oui java classes DISPLAY=:0.0 TERM=vt220 export DISPLAY TERM # keyboard commands stty erase set -o vi
jeremybaumont/Oracle-puppet-module
93d2ec09aab1a292ac4f4e2b42bb428609ad79db
Fix oracle user unix bash profile
diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index 261e86e..169e54a 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,79 +1,81 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } # Display main environment variables inforacle() { log "INFO" "ORACLE_SID=${ORACLE_SID}" log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" log "INFO" "ORACLE_HOME=${ORACLE_HOME}" } # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> +IMFLOG=/logs/oracle +NLS_LANG=American_America.UTF8 -export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID +export IMFLOG ORACLE_BASE NLS_LANG ORACLE_VERSION ORACLE_HOME ORACLE_SID # update lib path and command path -export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$HOME/bin:$PATH +export PATH=/opt/IMF/current/bin:$ORACLE_BASE/bin:$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$HOME/bin:$PATH export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH # oracle alias to speed up productivity alias rm='rm -i' alias sid='env|grep ORACLE_SID' alias i='inforacle' # display oracle main environment at login inforacle # set up X display and term for screen # kind of magic here but the silent installer need # to make an x connection in order to load oui java classes DISPLAY=:0.0 TERM=vt220 export DISPLAY TERM # keyboard commands stty erase set -o vi
jeremybaumont/Oracle-puppet-module
f2930681ea448f579007b49375dd91eaf41aa1de
Fix bug 000122
diff --git a/modules/oracle/templates/wagentDownload-template.erb b/modules/oracle/templates/wagentDownload-template.erb index 9c2d951..f43d34e 100644 --- a/modules/oracle/templates/wagentDownload-template.erb +++ b/modules/oracle/templates/wagentDownload-template.erb @@ -1,79 +1,78 @@ #!/usr/bin/bash EXITCODE=1 # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } cd <%= oemagent_bin_install_path %> log "INFO" "Current wokring directory: `pwd`" log "INFO" "Moving install binary to temp dir..." cp <%= agentDownload_filename %> /var/tmp/<%= agentDownload_filename %> cd /var/tmp log "INFO" "Current wokring directory: `pwd`" log "INFO" " Running oem agent silent install... " log "INFO" "./<%= agentDownload_filename %> -b <%= oemagent_dest_install_path %> -i <%= orainst_loc_path %> -m oem.wanadoo.nl -r 4889 " ./<%= agentDownload_filename %> -b <%= oemagent_dest_install_path %> -i <%= orainst_loc_path %> -m oem.wanadoo.nl -r 4889 log "INFO" "oem agent silent install finished..." sleep 60 orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" #oracle_install_log_path=$(find `find /var/tmp -type d -name \*agentDownload\* -print` -name \*.log -print) if [ -e "${oracle_install_log_path}" ]; then log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" else log_and_exit "ERROR" "Could not find an oracle install log file" fi test_pad() { local file=$1 sleep 5 grep 'Setup successful' $file if (( $? == 0 )); then - touch /var/opt/oracle/9.2.0.1_installed EXITCODE=0 touch /var/opt/oracle/oemagent_installed log_and_exit "INFO" "You have installed oem agent software" else log "INFO" "Not yet successful..." fi return 1 } while true; do test_pad ${oracle_install_log_path} sleep 5 done exit 0 diff --git a/modules/oracle/templates/wrapper_10.2.0.4-template.erb b/modules/oracle/templates/wrapper_10.2.0.4-template.erb index b782b2f..9181363 100644 --- a/modules/oracle/templates/wrapper_10.2.0.4-template.erb +++ b/modules/oracle/templates/wrapper_10.2.0.4-template.erb @@ -1,6 +1,6 @@ #!/usr/bin/sh su - oracle <<EOT cd /var/tmp -/wruninstaller_10.2.0.4_patchset.sh +./wruninstaller_10.2.0.4_patchset.sh EOT
jeremybaumont/Oracle-puppet-module
3737114ef609267bceea51dc4cb6cecbd23aa2d8
Fix bug 000121 fix log file resource
diff --git a/modules/oracle/manifests/directories.pp b/modules/oracle/manifests/directories.pp index 28ace95..e6cd0c8 100644 --- a/modules/oracle/manifests/directories.pp +++ b/modules/oracle/manifests/directories.pp @@ -1,523 +1,523 @@ # directories.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # puppet manages the following directories, they may not following OFA # but feel free to modify at your convenience # # ORACLE_BASE # /opt/app/oracle # # ORACLE_HOME # /opt/app/oracle/product/11.2.0/earth # # Inventory # /opt/app/oracle/oraInventory # # Data Directory # /ora06/dbsid/dbf/ # /ora07/dbsid/dbf/ # # Control Files # /ora01/dbsid/ctl # /ora02/dbsid/ctl # /ora03/dbsid/ctl # # Redo Logs # /ora01/dbsid/redo # /ora02/dbsid/redo # /ora03/dbsid/redo # # Archives # /ora04/dbsid/arch/ # # Dumps # /logs/oracle/diag/rdbms/db_name/db_sid/udump.... # # Flashback # /flash_recovery_area/dbsid # # RMAN # /rman-backup class oracle::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => false, mode => $mode } } # required directories oracle_dir { "var_opt": path => "/var/opt", ensure => directory, owner => "root", group => "root", before => File["var_opt_oracle"], mode => 755 } - oracle_dir { - "/logs": - path => "/logs", - ensure => directory, - owner => "root", - group => "root", - mode => 755 - } +# oracle_dir { +# "/logs": +# path => "/logs", +# ensure => directory, +# owner => "root", +# group => "root", +# mode => 755 +# } oracle_dir { "var_opt_oracle": path => "/var/opt/oracle", ensure => directory, owner => "oracle", group => "oinstall", require => File["var_opt"], mode => 755 } oracle_dir { "/opt/app": path => "/opt/app", ensure => directory, owner => "root", group => "root", before => File["oracle_base"], mode => 755 } $oracle_base_path = "/opt/app/oracle" $orainventory_path = "$oracle_base_path/oraInventory" file { "/var/opt/oracle/oraInst.loc": content => template("oracle/oraInst-template.erb"), ensure => present, force => true, owner => "oracle", group => "oinstall", mode => 644 } oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_product"] ], require => File["/opt/app"], mode => 755 } oracle_dir { "oracle_product": path => "${oracle_base_path}/product", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_major_version"], ], mode => 755 } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/product/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_product"] ], before => [ File["oracle_home"], ], mode => 755 } $oracle_home_path = "${oracle_base_path}/product/${oracle_major_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], ], mode => 755 } $oracle_ora01 = "/ora01" $oracle_ora02 = "/ora02" $oracle_ora03 = "/ora03" $oracle_ora04 = "/ora04" $oracle_ora06 = "/ora06" $oracle_ora07 = "/ora07" oracle_dir { "oracle_ora01": path => "${oracle_ora01}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora01_dbsid"], File["oracle_ora01_dbf"], ], mode => 755 } oracle_dir { "oracle_ora02": path => "${oracle_ora02}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora02_dbsid"], File["oracle_ora02_dbf"], ], mode => 755 } oracle_dir { "oracle_ora03": path => "${oracle_ora03}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora03_dbsid"], File["oracle_ora03_dbf"], ], mode => 755 } oracle_dir { "oracle_ora04": path => "${oracle_ora04}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora04_dbsid"], File["oracle_ora04_dbf"], ], mode => 755 } oracle_dir { "oracle_ora06": path => "${oracle_ora06}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora06_dbsid"], File["oracle_ora06_dbf"], ], mode => 755 } oracle_dir { "oracle_ora07": path => "${oracle_ora07}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora07_dbsid"], File["oracle_ora07_dbf"], ], mode => 755 } oracle_dir { "oracle_ora01_dbsid": path => "${oracle_ora01}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora01"], before => File["oracle_ora01_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora02_dbsid": path => "${oracle_ora02}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora02"], before => File["oracle_ora02_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora03_dbsid": path => "${oracle_ora03}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora03"], before => File["oracle_ora03_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora04_dbsid": path => "${oracle_ora04}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora04"], before => File["oracle_ora04_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora06_dbsid": path => "${oracle_ora06}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora06"], before => File["oracle_ora06_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora07_dbsid": path => "${oracle_ora07}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora07"], before => File["oracle_ora07_dbf"], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_dbf": path => "${oracle_ora01}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_dbf": path => "${oracle_ora02}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_dbf": path => "${oracle_ora03}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora04_dbf": path => "${oracle_ora04}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora04"], File["oracle_ora04_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora06_dbf": path => "${oracle_ora06}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora06"], File["oracle_ora06_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora07_dbf": path => "${oracle_ora07}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora07"], File["oracle_ora07_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_ctl": path => "${oracle_ora01}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_ctl": path => "${oracle_ora02}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_ctl": path => "${oracle_ora03}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_redo": path => "${oracle_ora01}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_redo": path => "${oracle_ora02}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_redo": path => "${oracle_ora03}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora04_arch": path => "${oracle_ora04}/${oracle_sid}/arch", ensure => directory, owner => "oracle", require => [ File["oracle_ora04"], File["oracle_ora04_dbsid"], ], group => "dba", mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755 } } # end of class oracle::directories
jeremybaumont/Oracle-puppet-module
97384ca7f370e286284a72b6328a4388254d5902
Fix bug 000120 about sysdba group
diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp index 77c4c63..195793e 100644 --- a/modules/oracle/manifests/software.pp +++ b/modules/oracle/manifests/software.pp @@ -1,493 +1,526 @@ # software.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::software { # You need the software cd/dvd/disks from Oracle downloaded # somewhere on the local machine $oracle_base_software = "/software/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version} or not yet implemented") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # start an x server, required for the # oracle installer exec { "9208_start_vfb": command => "start_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", creates => "/var/opt/oracle/started_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], File["/users/oracle/bin/start_vfb.sh"] ], timeout => "-1", } # build a script to run silent installer # of 9.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_9.2.0.1.sh": name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } + + # build a wrapper script + file{ + "wrapper_9.2.0.1.sh": + name => "${tmp_dir}/wrapper_9.2.0.1.sh", + content => template("oracle/wrapper_9.2.0.1-template.erb"), + mode => 755, + owner => "oracle", + } + # run silent installer of 9.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui-9201": - command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", + command => "wrapper_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.1_installed", - group => "oinstall", - user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ + File ["wrapper_9.2.0.1.sh"], File ["wruninstaller_9.2.0.1.sh"], Exec ["9208_start_vfb"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # before installing the 9.2.0.8 patchset # we need to shutdown all processes # using the oracle home directories file { "9208_stop_oracle_home_proc.sh": name => "${tmp_dir}/stop_oracle_home_proc.sh", content => template("oracle/stop_oracle_home_proc.erb"), mode => 755, owner =>"oracle", group => "oinstall", } exec { "9208_stop_oracle_home_proc": command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", group => "dba", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ Exec ["runinstaller-oui-9201"], File ["9208_stop_oracle_home_proc.sh"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" # build a script to run silent installer # of 9.2.0.8 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_9.2.0.8_patchset.sh": name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } + + # build a wrapper script + file{ + "wrapper_9.2.0.8.sh": + name => "${tmp_dir}/wrapper_9.2.0.8.sh", + content => template("oracle/wrapper_9.2.0.8-template.erb"), + mode => 755, + owner => "oracle", + } # run silent installer of 9.2.0.8 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui-9208": command => - "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", + "wrapper_9.2.0.8.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.8_patchset_installed", - group => "oinstall", - user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ + File ["wrapper_9.2.0.8.sh"], File ["wruninstaller_9.2.0.8_patchset.sh"], Exec ["runinstaller-oui-9201"], Exec ["9208_stop_oracle_home_proc"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # stop x server, required for the # oracle installer exec { "9208_stop_vfb": command => "stop_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", creates => "/var/opt/oracle/stopped_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], Exec["runinstaller-patchset-oui-9208"], File["/users/oracle/bin/stop_vfb.sh"] ], timeout => "-1", } file { "/var/opt/oracle/oracle_db_server_soft_installed": name => "/var/opt/oracle/oracle_db_server_soft_installed", mode => 0644, owner => "oracle", group => "dba", require => Exec["runinstaller-patchset-oui-9208"] } } "10.2.0.4": { $disk1_10201_path = "${oracle_base_software}/${architecture}/10.2.0.1/database" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_10201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # start an x server, required for the # oracle installer exec { "10204_start_vfb": command => "start_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", creates => "/var/opt/oracle/started_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], File["/users/oracle/bin/start_vfb.sh"] ], timeout => "-1", } # build a script to run silent installer # of 10.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_10.2.0.1.sh": name => "${tmp_dir}/wruninstaller_10.2.0.1.sh", content => template("oracle/wruninstaller_10.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } + + # build a wrapper script + file{ + "wrapper_10.2.0.1.sh": + name => "${tmp_dir}/wrapper_10.2.0.1.sh", + content => template("oracle/wrapper_10.2.0.1-template.erb"), + mode => 755, + owner => "oracle", + } # run silent installer of 10.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui-10201": - command => "wruninstaller_10.2.0.1.sh > ${tmp_dir}/runinstaller-oui_10.2.0.1.log", + command => "wrapper_10.2.0.1.sh > ${tmp_dir}/runinstaller-oui_10.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/10.2.0.1_installed", - group => "oinstall", - user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ + File ["wrapper_10.2.0.1.sh"], File ["wruninstaller_10.2.0.1.sh"], Exec ["10204_start_vfb"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # before installing the 10.2.0.4 patchset # we need to shutdown all processes # using the oracle home directories file { "10204_stop_oracle_home_proc.sh": name => "${tmp_dir}/stop_oracle_home_proc.sh", content => template("oracle/stop_oracle_home_proc.erb"), mode => 755, owner =>"oracle", group => "oinstall", } exec { "10204_stop_oracle_home_proc": command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", group => "dba", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ Exec ["runinstaller-oui-10201"], File ["10204_stop_oracle_home_proc.sh"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } $disk1_10204_patchset_path = "${oracle_base_software}/${architecture}/patchset_10.2.0.4/Disk1" $responsefile_patchset_path = "${disk1_10204_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_10204_patchset_path}/stage/products.xml" # build a script to run silent installer # of 10.2.0.4 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_10.2.0.4_patchset.sh": name => "${tmp_dir}/wruninstaller_10.2.0.4_patchset.sh", content => template("oracle/wruninstaller_10.2.0.4_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } + + # build a wrapper script + file{ + "wrapper_10.2.0.4.sh": + name => "${tmp_dir}/wrapper_10.2.0.4.sh", + content => template("oracle/wrapper_10.2.0.4-template.erb"), + mode => 755, + owner => "oracle", + } # run silent installer of 10.2.0.4 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui-10204": command => - "wruninstaller_10.2.0.4_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_10.2.0.4.log", + "wrapper_10.2.0.4.sh > ${tmp_dir}/runinstaller-patchset-oui_10.2.0.4.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/10.2.0.4_patchset_installed", - group => "oinstall", - user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ + File ["wrapper_10.2.0.4.sh"], File ["wruninstaller_10.2.0.4_patchset.sh"], Exec ["runinstaller-oui-10201"], Exec ["10204_stop_oracle_home_proc"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # stop x server, required for the # oracle installer exec { "10204_stop_vfb": command => "stop_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", creates => "/var/opt/oracle/stopped_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], Exec["runinstaller-patchset-oui-10204"], File["/users/oracle/bin/stop_vfb.sh"] ], timeout => "-1", } # file { "/var/opt/oracle/oracle_db_server_soft_installed": name => "/var/opt/oracle/oracle_db_server_soft_installed", mode => 0644, owner => "oracle", group => "dba", require => Exec["runinstaller-patchset-oui-10204"] } } #End of 10.2.0.4 } #End of case oracle_version }# End of solaris }# End of case operating_system }# End of define install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } diff --git a/modules/oracle/templates/wrapper_10.2.0.1-template.erb b/modules/oracle/templates/wrapper_10.2.0.1-template.erb new file mode 100644 index 0000000..1ea24c4 --- /dev/null +++ b/modules/oracle/templates/wrapper_10.2.0.1-template.erb @@ -0,0 +1,6 @@ +#!/usr/bin/sh +su - oracle <<EOT +cd /var/tmp +./wruninstaller_10.2.0.1.sh +EOT + diff --git a/modules/oracle/templates/wrapper_10.2.0.4-template.erb b/modules/oracle/templates/wrapper_10.2.0.4-template.erb new file mode 100644 index 0000000..b782b2f --- /dev/null +++ b/modules/oracle/templates/wrapper_10.2.0.4-template.erb @@ -0,0 +1,6 @@ +#!/usr/bin/sh +su - oracle <<EOT +cd /var/tmp +/wruninstaller_10.2.0.4_patchset.sh +EOT + diff --git a/modules/oracle/templates/wrapper_9.2.0.1-template.erb b/modules/oracle/templates/wrapper_9.2.0.1-template.erb new file mode 100644 index 0000000..91f06cf --- /dev/null +++ b/modules/oracle/templates/wrapper_9.2.0.1-template.erb @@ -0,0 +1,5 @@ +#!/usr/bin/sh +su - oracle <<EOT +cd /var/tmp +./wruninstaller_9.2.0.1.sh +EOT diff --git a/modules/oracle/templates/wrapper_9.2.0.8-template.erb b/modules/oracle/templates/wrapper_9.2.0.8-template.erb new file mode 100644 index 0000000..14deca5 --- /dev/null +++ b/modules/oracle/templates/wrapper_9.2.0.8-template.erb @@ -0,0 +1,5 @@ +#!/usr/bin/sh +su - oracle <<EOT +cd /var/tmp +./wruninstaller_9.2.0.8_patchset.sh +EOT
jeremybaumont/Oracle-puppet-module
17cb3510cae249acf5dba8196b9ade3d37904020
Delete display of Xsun process information at start
diff --git a/modules/oracle/files/users/oracle/bin/start_vfb.sh b/modules/oracle/files/users/oracle/bin/start_vfb.sh index 29c1cac..8359024 100755 --- a/modules/oracle/files/users/oracle/bin/start_vfb.sh +++ b/modules/oracle/files/users/oracle/bin/start_vfb.sh @@ -1,33 +1,34 @@ #!/usr/bin/bash XSUN=/usr/openwin/bin/Xsun DATE=`date '+%y%m%d.%H%M%S'` #Check XSUN is not running # -> tbd PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` if [ "$PROC_PID" == "" ]; then echo "XSUN Virtual Frame Buffer is not running" else echo "XSUN Virtual Frame Buffer is running. Please stop it first." ps -fe | grep -v grep | grep $XSUN exit 1 fi #- Start the XSUN Virtual Frame Buffer echo "Starting XSUN Virtual Frame Buffer" nohup $XSUN :0 +nkeyboard +nmouse -dev vfb screen 0 1024x768x8 2>&1 1>/var/tmp/start_vfb.$DATE.out & sleep 3 #Check XSUN Virtual Frame Buffer has started # -> tbd PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` if [ "$PROC_PID" == "" ]; then echo "XSUN Virtual Frame Buffer did not start successfully ;-(" exit 1 else echo "XSUN Virtual Frame Buffer start successfully !" - ps -fe | grep -v grep | grep $XSUN +# ps -fe | grep -v grep | grep $XSUN fi touch /var/opt/oracle/started_vfb +exit 0
jeremybaumont/Oracle-puppet-module
b133d526b89d55a3d78da881065a3979cf6da060
Add install of oem agent
diff --git a/modules/oracle/files/users/oracle/bin/start_vfb.sh b/modules/oracle/files/users/oracle/bin/start_vfb.sh index 8aa9915..29c1cac 100755 --- a/modules/oracle/files/users/oracle/bin/start_vfb.sh +++ b/modules/oracle/files/users/oracle/bin/start_vfb.sh @@ -1,32 +1,33 @@ #!/usr/bin/bash XSUN=/usr/openwin/bin/Xsun DATE=`date '+%y%m%d.%H%M%S'` #Check XSUN is not running # -> tbd PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` if [ "$PROC_PID" == "" ]; then echo "XSUN Virtual Frame Buffer is not running" else echo "XSUN Virtual Frame Buffer is running. Please stop it first." ps -fe | grep -v grep | grep $XSUN exit 1 fi #- Start the XSUN Virtual Frame Buffer echo "Starting XSUN Virtual Frame Buffer" nohup $XSUN :0 +nkeyboard +nmouse -dev vfb screen 0 1024x768x8 2>&1 1>/var/tmp/start_vfb.$DATE.out & sleep 3 #Check XSUN Virtual Frame Buffer has started # -> tbd PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` if [ "$PROC_PID" == "" ]; then echo "XSUN Virtual Frame Buffer did not start successfully ;-(" exit 1 else echo "XSUN Virtual Frame Buffer start successfully !" ps -fe | grep -v grep | grep $XSUN fi +touch /var/opt/oracle/started_vfb diff --git a/modules/oracle/files/users/oracle/bin/stop_vfb.sh b/modules/oracle/files/users/oracle/bin/stop_vfb.sh index 6bb2a1f..248fb83 100755 --- a/modules/oracle/files/users/oracle/bin/stop_vfb.sh +++ b/modules/oracle/files/users/oracle/bin/stop_vfb.sh @@ -1,22 +1,24 @@ #!/usr/bin/bash XSUN=/usr/openwin/bin/Xsun DATE=`date '+%y%m%d.%H%M%S'` #Check XSUN is not running # -> tbd PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` if [ "$PROC_PID" == "" ]; then echo "XSUN Virtual Frame Buffer is not running" else echo "XSUN Virtual Frame Buffer is running. Stoppin it ..." kill -9 $PROC_PID > /var/tmp/stop_vfb_$DATE.out if [ $? -eq 0 ]; then echo "XSUN Virtual Frame Buffer stopped." + touch /var/opt/oracle/stopped_vfb exit 0 else echo "XSUN Virtual Frame Buffer failed to be stopped ;-(" exit 1 fi fi + diff --git a/modules/oracle/manifests/oemagent.pp b/modules/oracle/manifests/oemagent.pp new file mode 100644 index 0000000..fcd2436 --- /dev/null +++ b/modules/oracle/manifests/oemagent.pp @@ -0,0 +1,79 @@ +class oracle::oemagent { + + $oemagent_base_software = "/software/oracle/oem_agent" + $oemagent_bin_install_path = "${oemagent_base_software}/${architecture}/" + $tmp_dir = "/var/tmp" + $orainst_loc_path = "/var/opt/oracle/oraInst.loc" + $oemagent_dest_install_path = "/opt/app/oracle/product" + $orainventory_path = "/opt/app/oracle/oraInventory" + + case $architecture { + default: { + err("unknown architecture value ${architecture} or not yet implemented") + } # end of default + sparc32,sparc64: { + + $agentDownload_filename = "agentDownload.solaris" + + file{ + "wagentDownload-10204-sparc": + name => "${tmp_dir}/wagentDownload-10204.sh", + content => template("oracle/wagentDownload-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + require => File["/var/opt/oracle/oracle_db_server_soft_installed"], + } + + exec { + "run_wagentDownload-10204-sparc": + command => "wagentDownload-10204.sh > ${tmp_dir}/run_wagentDownload-10204-sparc.log", + path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", + "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + creates => "/var/opt/oracle/oemagent_installed", + group => "oinstall", + user => "oracle", + logoutput => true, + returns => [0,1], + require => File["wagentDownload-10204-sparc"], + timeout => "-1", + } + + } # end of sparc32,sparc64 + x86-64: { + + $agentDownload_filename = "agentDownload.solaris_x64" + + file{ + "wagentDownload-10205-x86-64": + name => "${tmp_dir}/wagentDownload-10205.sh", + content => template("oracle/wagentDownload-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + require => File["/var/opt/oracle/oracle_db_server_soft_installed"], + } + + + exec { + "run_wagentDownload-10205-x86-64": + command => "wagentDownload-10205.sh > ${tmp_dir}/run_wagentDownload-10205-x86-64.log", + path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", + "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + creates => "/var/opt/oracle/oemagent_installed", + group => "oinstall", + user => "oracle", + logoutput => true, + returns => [0,1], + require => File["wagentDownload-10205-x86-64"], + timeout => "-1", + } + + } # end of x86-64 + + + } # end of case + +} # end of class diff --git a/modules/oracle/manifests/server.pp b/modules/oracle/manifests/server.pp index 6747639..7252b57 100644 --- a/modules/oracle/manifests/server.pp +++ b/modules/oracle/manifests/server.pp @@ -1,32 +1,33 @@ # server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::server { include oracle::administrators include oracle::system_packages } # end of class oracle::server class oracle::server::database inherits oracle::server { include oracle::directories include oracle::system_profile } class oracle::server::database::enterprise inherits oracle::server::database { include oracle::software + include oracle::oemagent } diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp index bb34f5a..77c4c63 100644 --- a/modules/oracle/manifests/software.pp +++ b/modules/oracle/manifests/software.pp @@ -1,469 +1,493 @@ # software.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::software { # You need the software cd/dvd/disks from Oracle downloaded # somewhere on the local machine $oracle_base_software = "/software/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version} or not yet implemented") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # start an x server, required for the # oracle installer exec { "9208_start_vfb": command => "start_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", + creates => "/var/opt/oracle/started_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], File["/users/oracle/bin/start_vfb.sh"] ], timeout => "-1", } # build a script to run silent installer # of 9.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_9.2.0.1.sh": name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui-9201": command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.1_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.1.sh"], Exec ["9208_start_vfb"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # before installing the 9.2.0.8 patchset # we need to shutdown all processes # using the oracle home directories file { "9208_stop_oracle_home_proc.sh": name => "${tmp_dir}/stop_oracle_home_proc.sh", content => template("oracle/stop_oracle_home_proc.erb"), mode => 755, owner =>"oracle", group => "oinstall", } exec { "9208_stop_oracle_home_proc": command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", group => "dba", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ Exec ["runinstaller-oui-9201"], File ["9208_stop_oracle_home_proc.sh"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" # build a script to run silent installer # of 9.2.0.8 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_9.2.0.8_patchset.sh": name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.8 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui-9208": command => "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.8_patchset_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.8_patchset.sh"], Exec ["runinstaller-oui-9201"], Exec ["9208_stop_oracle_home_proc"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # stop x server, required for the # oracle installer exec { "9208_stop_vfb": command => "stop_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", + creates => "/var/opt/oracle/stopped_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], Exec["runinstaller-patchset-oui-9208"], File["/users/oracle/bin/stop_vfb.sh"] ], timeout => "-1", } + file { + "/var/opt/oracle/oracle_db_server_soft_installed": + name => "/var/opt/oracle/oracle_db_server_soft_installed", + mode => 0644, + owner => "oracle", + group => "dba", + require => Exec["runinstaller-patchset-oui-9208"] + } + } "10.2.0.4": { $disk1_10201_path = "${oracle_base_software}/${architecture}/10.2.0.1/database" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_10201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # start an x server, required for the # oracle installer exec { "10204_start_vfb": command => "start_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", + creates => "/var/opt/oracle/started_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], File["/users/oracle/bin/start_vfb.sh"] ], timeout => "-1", } # build a script to run silent installer # of 10.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_10.2.0.1.sh": name => "${tmp_dir}/wruninstaller_10.2.0.1.sh", content => template("oracle/wruninstaller_10.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 10.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui-10201": command => "wruninstaller_10.2.0.1.sh > ${tmp_dir}/runinstaller-oui_10.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/10.2.0.1_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_10.2.0.1.sh"], Exec ["10204_start_vfb"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # before installing the 10.2.0.4 patchset # we need to shutdown all processes # using the oracle home directories file { "10204_stop_oracle_home_proc.sh": name => "${tmp_dir}/stop_oracle_home_proc.sh", content => template("oracle/stop_oracle_home_proc.erb"), mode => 755, owner =>"oracle", group => "oinstall", } exec { "10204_stop_oracle_home_proc": command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", group => "dba", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ Exec ["runinstaller-oui-10201"], File ["10204_stop_oracle_home_proc.sh"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } $disk1_10204_patchset_path = "${oracle_base_software}/${architecture}/patchset_10.2.0.4/Disk1" $responsefile_patchset_path = "${disk1_10204_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_10204_patchset_path}/stage/products.xml" # build a script to run silent installer # of 10.2.0.4 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_10.2.0.4_patchset.sh": name => "${tmp_dir}/wruninstaller_10.2.0.4_patchset.sh", content => template("oracle/wruninstaller_10.2.0.4_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 10.2.0.4 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui-10204": command => "wruninstaller_10.2.0.4_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_10.2.0.4.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/10.2.0.4_patchset_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_10.2.0.4_patchset.sh"], Exec ["runinstaller-oui-10201"], Exec ["10204_stop_oracle_home_proc"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # stop x server, required for the # oracle installer exec { "10204_stop_vfb": command => "stop_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", + creates => "/var/opt/oracle/stopped_vfb", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], Exec["runinstaller-patchset-oui-10204"], File["/users/oracle/bin/stop_vfb.sh"] ], timeout => "-1", } # - } - } - } - } - } + file { + "/var/opt/oracle/oracle_db_server_soft_installed": + name => "/var/opt/oracle/oracle_db_server_soft_installed", + mode => 0644, + owner => "oracle", + group => "dba", + require => Exec["runinstaller-patchset-oui-10204"] + } + } #End of 10.2.0.4 + } #End of case oracle_version + + + }# End of solaris + + }# End of case operating_system + }# End of define install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } diff --git a/modules/oracle/templates/wagentDownload-template.erb b/modules/oracle/templates/wagentDownload-template.erb new file mode 100644 index 0000000..9c2d951 --- /dev/null +++ b/modules/oracle/templates/wagentDownload-template.erb @@ -0,0 +1,79 @@ +#!/usr/bin/bash + +EXITCODE=1 + +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + + + +cd <%= oemagent_bin_install_path %> +log "INFO" "Current wokring directory: `pwd`" + +log "INFO" "Moving install binary to temp dir..." +cp <%= agentDownload_filename %> /var/tmp/<%= agentDownload_filename %> +cd /var/tmp +log "INFO" "Current wokring directory: `pwd`" + + +log "INFO" " Running oem agent silent install... " +log "INFO" "./<%= agentDownload_filename %> -b <%= oemagent_dest_install_path %> -i <%= orainst_loc_path %> -m oem.wanadoo.nl -r 4889 " + +./<%= agentDownload_filename %> -b <%= oemagent_dest_install_path %> -i <%= orainst_loc_path %> -m oem.wanadoo.nl -r 4889 +log "INFO" "oem agent silent install finished..." + +sleep 60 +orainventory_path=<%= orainventory_path %> +oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` +oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" +#oracle_install_log_path=$(find `find /var/tmp -type d -name \*agentDownload\* -print` -name \*.log -print) + +if [ -e "${oracle_install_log_path}" ]; then + log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" +else + log_and_exit "ERROR" "Could not find an oracle install log file" +fi + + +test_pad() +{ + local file=$1 + sleep 5 + grep 'Setup successful' $file + if (( $? == 0 )); then + touch /var/opt/oracle/9.2.0.1_installed + EXITCODE=0 + touch /var/opt/oracle/oemagent_installed + log_and_exit "INFO" "You have installed oem agent software" + else + log "INFO" "Not yet successful..." + fi + + return 1 +} + +while true; do + test_pad ${oracle_install_log_path} + sleep 5 +done + + +exit 0 diff --git a/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb b/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb index b7ed2b8..ecacfa5 100644 --- a/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb +++ b/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb @@ -1,94 +1,95 @@ #!/usr/bin/bash EXITCODE=1 # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } sleep 90 log "INFO" "Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" n_configurationOption=3 " cd <%= disk1_10204_patchset_path %> log "INFO" "Current wokring directory: `pwd`" log "INFO" "Stopping running processes in oracle home..." kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep -v grep |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "Running processes in oracle home stopped !" else log_and_exit "ERROR" "Could not stopped running processes in oracle home properly: ${kill_isqlplus_cmd}" fi log "INFO" "Stopping isqlplus..." kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep isqlplus |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "isqlplus stopped !" else log_and_exit "ERROR" "Could not stopped isqlplus properly: ${kill_isqlplus_cmd}" fi log "INFO" "Stopping oracle httpd server..." $ORACLE_HOME/Apache/Apache/bin/apachectl stop kill_httpd_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep httpd |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "httpd stopped !" else log_and_exit "ERROR" "Could not stopped httpd properly: ${kill_httpd_cmd}" fi log "INFO" "The runinstaller is starting..." ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" n_configurationOption=3 log "INFO" "The runinstaller is started..." sleep 120 orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" if [ -e "${oracle_install_log_path}" ]; then log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" else log_and_exit "ERROR" "Could not find an oracle install log file" fi test_pad() { local file=$1 sleep 5 grep 'was successful' $file if (( $? == 0 )); then EXITCODE=0 touch /var/opt/oracle/10.2.0.4_patchset_installed + touch /var/opt/oracle/oracle_db_server_soft_installed log_and_exit "INFO" "You have installed 10.2.0.4 database server patch software" else log "INFO" "Not yet successful..." fi return 1 } while true; do test_pad ${oracle_install_log_path} sleep 5 done exit 0 diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb index 1a1ae6c..74f8e7a 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb @@ -1,94 +1,95 @@ #!/usr/bin/bash EXITCODE=1 # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } sleep 90 log "INFO" "Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" " cd <%= disk1_9208_patchset_path %> log "INFO" "Current wokring directory: `pwd`" log "INFO" "Stopping running processes in oracle home..." kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep -v grep |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "Running processes in oracle home stopped !" else log_and_exit "ERROR" "Could not stopped running processes in oracle home properly: ${kill_isqlplus_cmd}" fi log "INFO" "Stopping isqlplus..." kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep isqlplus |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "isqlplus stopped !" else log_and_exit "ERROR" "Could not stopped isqlplus properly: ${kill_isqlplus_cmd}" fi log "INFO" "Stopping oracle httpd server..." $ORACLE_HOME/Apache/Apache/bin/apachectl stop kill_httpd_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep httpd |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "httpd stopped !" else log_and_exit "ERROR" "Could not stopped httpd properly: ${kill_httpd_cmd}" fi log "INFO" "The runinstaller is starting..." ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" log "INFO" "The runinstaller is started..." sleep 120 orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" #oracle_install_log_path=`find ${oracinventory_path}/logs -type f -print| xargs -n 1 -i egrep -l "TOPLEVEL_COMPONENT.*9.2.0.8" {}` if [ -e "${oracle_install_log_path}" ]; then log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" else log_and_exit "ERROR" "Could not find an oracle install log file" fi test_pad() { local file=$1 sleep 5 grep 'was successful' $file if (( $? == 0 )); then EXITCODE=0 touch /var/opt/oracle/9.2.0.8_patchset_installed + touch /var/opt/oracle/oracle_db_server_soft_installed log_and_exit "INFO" "You have installed 9.2.0.8 database server patch software" else log "INFO" "Not yet successful..." fi return 1 } while true; do test_pad ${oracle_install_log_path} sleep 5 done exit 0
jeremybaumont/Oracle-puppet-module
2e35c8c5efe338f7d75d790f0cdcc2dd31084c9c
Add exec resource to install 10.2.0.4 software
diff --git a/modules/oracle/manifests/directories.pp b/modules/oracle/manifests/directories.pp index bc614cf..28ace95 100644 --- a/modules/oracle/manifests/directories.pp +++ b/modules/oracle/manifests/directories.pp @@ -1,522 +1,523 @@ # directories.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # puppet manages the following directories, they may not following OFA # but feel free to modify at your convenience # # ORACLE_BASE # /opt/app/oracle # # ORACLE_HOME # /opt/app/oracle/product/11.2.0/earth # # Inventory # /opt/app/oracle/oraInventory # # Data Directory # /ora06/dbsid/dbf/ # /ora07/dbsid/dbf/ # # Control Files # /ora01/dbsid/ctl # /ora02/dbsid/ctl # /ora03/dbsid/ctl # # Redo Logs # /ora01/dbsid/redo # /ora02/dbsid/redo # /ora03/dbsid/redo # # Archives # /ora04/dbsid/arch/ # # Dumps # /logs/oracle/diag/rdbms/db_name/db_sid/udump.... # # Flashback # /flash_recovery_area/dbsid # # RMAN # /rman-backup class oracle::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => false, mode => $mode } } # required directories oracle_dir { "var_opt": path => "/var/opt", ensure => directory, owner => "root", group => "root", before => File["var_opt_oracle"], mode => 755 } oracle_dir { "/logs": path => "/logs", ensure => directory, owner => "root", group => "root", mode => 755 } oracle_dir { "var_opt_oracle": path => "/var/opt/oracle", ensure => directory, owner => "oracle", group => "oinstall", require => File["var_opt"], mode => 755 } oracle_dir { "/opt/app": path => "/opt/app", ensure => directory, owner => "root", group => "root", before => File["oracle_base"], mode => 755 } $oracle_base_path = "/opt/app/oracle" $orainventory_path = "$oracle_base_path/oraInventory" file { "/var/opt/oracle/oraInst.loc": content => template("oracle/oraInst-template.erb"), ensure => present, force => true, owner => "oracle", group => "oinstall", mode => 644 } oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_product"] ], require => File["/opt/app"], mode => 755 } oracle_dir { "oracle_product": path => "${oracle_base_path}/product", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_major_version"], ], + mode => 755 } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/product/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_product"] ], before => [ File["oracle_home"], ], mode => 755 } $oracle_home_path = "${oracle_base_path}/product/${oracle_major_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], ], mode => 755 } $oracle_ora01 = "/ora01" $oracle_ora02 = "/ora02" $oracle_ora03 = "/ora03" $oracle_ora04 = "/ora04" $oracle_ora06 = "/ora06" $oracle_ora07 = "/ora07" oracle_dir { "oracle_ora01": path => "${oracle_ora01}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora01_dbsid"], File["oracle_ora01_dbf"], ], mode => 755 } oracle_dir { "oracle_ora02": path => "${oracle_ora02}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora02_dbsid"], File["oracle_ora02_dbf"], ], mode => 755 } oracle_dir { "oracle_ora03": path => "${oracle_ora03}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora03_dbsid"], File["oracle_ora03_dbf"], ], mode => 755 } oracle_dir { "oracle_ora04": path => "${oracle_ora04}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora04_dbsid"], File["oracle_ora04_dbf"], ], mode => 755 } oracle_dir { "oracle_ora06": path => "${oracle_ora06}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora06_dbsid"], File["oracle_ora06_dbf"], ], mode => 755 } oracle_dir { "oracle_ora07": path => "${oracle_ora07}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora07_dbsid"], File["oracle_ora07_dbf"], ], mode => 755 } oracle_dir { "oracle_ora01_dbsid": path => "${oracle_ora01}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora01"], before => File["oracle_ora01_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora02_dbsid": path => "${oracle_ora02}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora02"], before => File["oracle_ora02_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora03_dbsid": path => "${oracle_ora03}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora03"], before => File["oracle_ora03_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora04_dbsid": path => "${oracle_ora04}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora04"], before => File["oracle_ora04_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora06_dbsid": path => "${oracle_ora06}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora06"], before => File["oracle_ora06_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora07_dbsid": path => "${oracle_ora07}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora07"], before => File["oracle_ora07_dbf"], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_dbf": path => "${oracle_ora01}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_dbf": path => "${oracle_ora02}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_dbf": path => "${oracle_ora03}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora04_dbf": path => "${oracle_ora04}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora04"], File["oracle_ora04_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora06_dbf": path => "${oracle_ora06}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora06"], File["oracle_ora06_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora07_dbf": path => "${oracle_ora07}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora07"], File["oracle_ora07_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_ctl": path => "${oracle_ora01}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_ctl": path => "${oracle_ora02}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_ctl": path => "${oracle_ora03}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_redo": path => "${oracle_ora01}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_redo": path => "${oracle_ora02}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_redo": path => "${oracle_ora03}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora04_arch": path => "${oracle_ora04}/${oracle_sid}/arch", ensure => directory, owner => "oracle", require => [ File["oracle_ora04"], File["oracle_ora04_dbsid"], ], group => "dba", mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755 } } # end of class oracle::directories diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp index 3225838..bb34f5a 100644 --- a/modules/oracle/manifests/software.pp +++ b/modules/oracle/manifests/software.pp @@ -1,260 +1,469 @@ # software.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::software { # You need the software cd/dvd/disks from Oracle downloaded # somewhere on the local machine - $oracle_base_software = "/opt/applications/repository/oracle/database_server" + $oracle_base_software = "/software/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version} or not yet implemented") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # start an x server, required for the # oracle installer exec { - "start_vfb": + "9208_start_vfb": command => "start_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], File["/users/oracle/bin/start_vfb.sh"] ], timeout => "-1", } # build a script to run silent installer # of 9.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_9.2.0.1.sh": name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { - "runinstaller-oui": + "runinstaller-oui-9201": command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.1_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.1.sh"], - Exec ["start_vfb"], + Exec ["9208_start_vfb"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # before installing the 9.2.0.8 patchset # we need to shutdown all processes # using the oracle home directories file { - "stop_oracle_home_proc.sh": + "9208_stop_oracle_home_proc.sh": name => "${tmp_dir}/stop_oracle_home_proc.sh", content => template("oracle/stop_oracle_home_proc.erb"), mode => 755, owner =>"oracle", group => "oinstall", } exec { - "stop_oracle_home_proc": + "9208_stop_oracle_home_proc": command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", group => "dba", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ - Exec ["runinstaller-oui"], - File ["stop_oracle_home_proc.sh"], + Exec ["runinstaller-oui-9201"], + File ["9208_stop_oracle_home_proc.sh"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" # build a script to run silent installer # of 9.2.0.8 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_9.2.0.8_patchset.sh": name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.8 Disk 1 # Orable database server software # enterprise edition patchset exec { - "runinstaller-patchset-oui": + "runinstaller-patchset-oui-9208": command => "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.8_patchset_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.8_patchset.sh"], - Exec ["runinstaller-oui"], - Exec ["stop_oracle_home_proc"], + Exec ["runinstaller-oui-9201"], + Exec ["9208_stop_oracle_home_proc"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } # stop x server, required for the # oracle installer exec { - "stop_vfb": + "9208_stop_vfb": command => "stop_vfb.sh", path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "/users/oracle/bin", group => "root", user => "root", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File["/users/oracle/bin/"], - Exec["runinstaller-patchset-oui"], + Exec["runinstaller-patchset-oui-9208"], File["/users/oracle/bin/stop_vfb.sh"] ], timeout => "-1", } } "10.2.0.4": { + $disk1_10201_path = "${oracle_base_software}/${architecture}/10.2.0.1/database" + $current_oracle_home = $oracle::directories::oracle_home_path + $responsefile_path = "${disk1_10201_path}/response/enterprise.rsp" + $current_oracle_base = $oracle::directories::oracle_base_path + $orainventory_path = "$current_oracle_base/oraInventory" + $tmp_dir = "/var/tmp" + + + # start an x server, required for the + # oracle installer + exec { + "10204_start_vfb": + command => "start_vfb.sh", + path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", + "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "/users/oracle/bin", + group => "root", + user => "root", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File["/users/oracle/bin/"], + File["/users/oracle/bin/start_vfb.sh"] + ], + timeout => "-1", + } + + # build a script to run silent installer + # of 10.2.0.1 Disk 1 Oracle database + # server software enterprise edition + file{ + "wruninstaller_10.2.0.1.sh": + name => "${tmp_dir}/wruninstaller_10.2.0.1.sh", + content => template("oracle/wruninstaller_10.2.0.1-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + } + + # run silent installer of 10.2.0.1 Disk 1 + # Orable database server software + # enterprise edition + exec { + "runinstaller-oui-10201": + command => "wruninstaller_10.2.0.1.sh > ${tmp_dir}/runinstaller-oui_10.2.0.1.log", + path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", + "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + creates => "/var/opt/oracle/10.2.0.1_installed", + group => "oinstall", + user => "oracle", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File ["wruninstaller_10.2.0.1.sh"], + Exec ["10204_start_vfb"], + File["var_opt_oracle"], + File["oracle_home"], + File["oracle_base"], + File["/users/oracle/.bash_profile"], + File["/var/opt/oracle/oraInst.loc"], + File["/users/oracle/.bashrc"], + File["/users/oracle"], + User["oracle"], + Group["dba"], + Group["oinstall"] + ], + timeout => "-1", + } + + # before installing the 10.2.0.4 patchset + # we need to shutdown all processes + # using the oracle home directories + file { + "10204_stop_oracle_home_proc.sh": + name => "${tmp_dir}/stop_oracle_home_proc.sh", + content => template("oracle/stop_oracle_home_proc.erb"), + mode => 755, + owner =>"oracle", + group => "oinstall", + + } + + exec { + "10204_stop_oracle_home_proc": + command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", + path => ["/usr/bin", + "/usr/sbin", + ".", + "/opt/csw/bin", + "/usr/sbin", + "/usr/bin", + "/usr/dt/bin", + "/usr/openwin/bin", + "/usr/ccs/bin", + "/usr/sfw/bin", + "/usr/perl5/5.8.4/bin", + "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + group => "dba", + user => "oracle", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + Exec ["runinstaller-oui-10201"], + File ["10204_stop_oracle_home_proc.sh"], + File["var_opt_oracle"], + File["oracle_home"], + File["oracle_base"], + File["/users/oracle/.bash_profile"], + File["/var/opt/oracle/oraInst.loc"], + File["/users/oracle/.bashrc"], + File["/users/oracle"], + User["oracle"], + Group["dba"], + Group["oinstall"] + ], + timeout => "-1", + + } + + + $disk1_10204_patchset_path = "${oracle_base_software}/${architecture}/patchset_10.2.0.4/Disk1" + $responsefile_patchset_path = "${disk1_10204_patchset_path}/response/patchset.rsp" + $products_patchset_path = "${disk1_10204_patchset_path}/stage/products.xml" + + # build a script to run silent installer + # of 10.2.0.4 Disk 1 Oracle database + # server software enterprise edition + # patchset + file{ + "wruninstaller_10.2.0.4_patchset.sh": + name => "${tmp_dir}/wruninstaller_10.2.0.4_patchset.sh", + content => template("oracle/wruninstaller_10.2.0.4_patchset-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + } + + # run silent installer of 10.2.0.4 Disk 1 + # Orable database server software + # enterprise edition patchset + exec { + "runinstaller-patchset-oui-10204": + command => + "wruninstaller_10.2.0.4_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_10.2.0.4.log", + path => ["/usr/bin", + "/usr/sbin", + ".", + "/opt/csw/bin", + "/usr/sbin", + "/usr/bin", + "/usr/dt/bin", + "/usr/openwin/bin", + "/usr/ccs/bin", + "/usr/sfw/bin", + "/usr/perl5/5.8.4/bin", + "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + creates => "/var/opt/oracle/10.2.0.4_patchset_installed", + group => "oinstall", + user => "oracle", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File ["wruninstaller_10.2.0.4_patchset.sh"], + Exec ["runinstaller-oui-10201"], + Exec ["10204_stop_oracle_home_proc"], + File["var_opt_oracle"], + File["oracle_home"], + File["oracle_base"], + File["/users/oracle/.bash_profile"], + File["/var/opt/oracle/oraInst.loc"], + File["/users/oracle/.bashrc"], + File["/users/oracle"], + User["oracle"], + Group["dba"], + Group["oinstall"] + ], + timeout => "-1", + } + + # stop x server, required for the + # oracle installer + exec { + "10204_stop_vfb": + command => "stop_vfb.sh", + path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", + "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "/users/oracle/bin", + group => "root", + user => "root", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File["/users/oracle/bin/"], + Exec["runinstaller-patchset-oui-10204"], + File["/users/oracle/bin/stop_vfb.sh"] + ], + timeout => "-1", + } + + # + } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } diff --git a/modules/oracle/manifests/system_packages.pp b/modules/oracle/manifests/system_packages.pp index bed9217..8e888af 100644 --- a/modules/oracle/manifests/system_packages.pp +++ b/modules/oracle/manifests/system_packages.pp @@ -1,70 +1,70 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" - case $oracle_major_version { - "10g": { + case $oracle_version { + "10.2.0.4": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("INFO - the architecture $architecture is not yet supported by class system_packages.") } } } - "9i": { + "9.2.0.8": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("INFO - the architecture $architecture is not yet supported by class system_packages.") } } } default: { - fail("INFO - the oracle version $oracle_major_version is not + fail("INFO - the oracle version $oracle_version is not yet support by class system_packages.") } } } } notify {"INFO - the operating system is ${operatingsystem}": } notify {"INFO - the architecture is ${architecture}": } notify {"INFO - the architecture is ${oracle_major_version}": } notify {"INFO - the list of packages required is ${system_packages}": } package { $system_packages: ensure => installed, provider => $sun_provider } }# end of class oracle::system_packages diff --git a/modules/oracle/templates/wruninstaller_10.2.0.1-template.erb b/modules/oracle/templates/wruninstaller_10.2.0.1-template.erb new file mode 100644 index 0000000..d0370c5 --- /dev/null +++ b/modules/oracle/templates/wruninstaller_10.2.0.1-template.erb @@ -0,0 +1,69 @@ +#!/usr/bin/bash + +EXITCODE=1 + +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + +log "INFO" " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" n_configurationOption=3 " + +cd <%= disk1_10201_path %> +log "INFO" "Current wokring directory: `pwd`" + +log "INFO" "The runinstaller is starting..." +./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" n_configurationOption=3 +log "INFO" "The runinstaller is started..." + +sleep 120 +orainventory_path=<%= orainventory_path %> +oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` +oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" + + +if [ -e "${oracle_install_log_path}" ]; then + log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" +else + log_and_exit "ERROR" "Could not find an oracle install log file" +fi + + +test_pad() +{ + local file=$1 + sleep 5 + grep 'was successful' $file + if (( $? == 0 )); then + touch /var/opt/oracle/10.2.0.1_installed + EXITCODE=0 + log_and_exit "INFO" "You have installed 10.2.0.1 database server software" + else + log "INFO" "Not yet successful..." + fi + + return 1 +} + +while true; do + test_pad ${oracle_install_log_path} + sleep 5 +done + +exit 0 diff --git a/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb b/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb new file mode 100644 index 0000000..b7ed2b8 --- /dev/null +++ b/modules/oracle/templates/wruninstaller_10.2.0.4_patchset-template.erb @@ -0,0 +1,94 @@ +#!/usr/bin/bash + +EXITCODE=1 + +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + +sleep 90 + +log "INFO" "Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" n_configurationOption=3 " + +cd <%= disk1_10204_patchset_path %> +log "INFO" "Current wokring directory: `pwd`" + +log "INFO" "Stopping running processes in oracle home..." +kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep -v grep |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +if [ $? -eq 0 ]; then + log "INFO" "Running processes in oracle home stopped !" +else + log_and_exit "ERROR" "Could not stopped running processes in oracle home properly: ${kill_isqlplus_cmd}" +fi + +log "INFO" "Stopping isqlplus..." +kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep isqlplus |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +if [ $? -eq 0 ]; then + log "INFO" "isqlplus stopped !" +else + log_and_exit "ERROR" "Could not stopped isqlplus properly: ${kill_isqlplus_cmd}" +fi + +log "INFO" "Stopping oracle httpd server..." +$ORACLE_HOME/Apache/Apache/bin/apachectl stop +kill_httpd_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep httpd |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +if [ $? -eq 0 ]; then + log "INFO" "httpd stopped !" +else + log_and_exit "ERROR" "Could not stopped httpd properly: ${kill_httpd_cmd}" +fi + + +log "INFO" "The runinstaller is starting..." +./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" n_configurationOption=3 +log "INFO" "The runinstaller is started..." + +sleep 120 +orainventory_path=<%= orainventory_path %> +oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` +oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" + + +if [ -e "${oracle_install_log_path}" ]; then + log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" +else + log_and_exit "ERROR" "Could not find an oracle install log file" +fi + +test_pad() +{ +local file=$1 +sleep 5 +grep 'was successful' $file +if (( $? == 0 )); then + EXITCODE=0 + touch /var/opt/oracle/10.2.0.4_patchset_installed + log_and_exit "INFO" "You have installed 10.2.0.4 database server patch software" +else + log "INFO" "Not yet successful..." +fi +return 1 +} + +while true; do + test_pad ${oracle_install_log_path} + sleep 5 +done +exit 0 diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb index 0c049b5..1a1ae6c 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb @@ -1,100 +1,94 @@ #!/usr/bin/bash EXITCODE=1 # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } sleep 90 log "INFO" "Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" " cd <%= disk1_9208_patchset_path %> log "INFO" "Current wokring directory: `pwd`" log "INFO" "Stopping running processes in oracle home..." -kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep applications | grep -v grep |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep -v grep |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "Running processes in oracle home stopped !" else log_and_exit "ERROR" "Could not stopped running processes in oracle home properly: ${kill_isqlplus_cmd}" fi log "INFO" "Stopping isqlplus..." -kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep applications | grep isqlplus |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep isqlplus |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "isqlplus stopped !" else log_and_exit "ERROR" "Could not stopped isqlplus properly: ${kill_isqlplus_cmd}" fi log "INFO" "Stopping oracle httpd server..." $ORACLE_HOME/Apache/Apache/bin/apachectl stop -kill_httpd_cmd=`/usr/ucb/ps wwwaux | grep applications | grep httpd |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +kill_httpd_cmd=`/usr/ucb/ps wwwaux | grep 'app/oracle/product' | grep httpd |awk '{print $2}' |xargs -n 1 -i kill -9 {}` if [ $? -eq 0 ]; then log "INFO" "httpd stopped !" else log_and_exit "ERROR" "Could not stopped httpd properly: ${kill_httpd_cmd}" fi log "INFO" "The runinstaller is starting..." ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" log "INFO" "The runinstaller is started..." sleep 120 orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" #oracle_install_log_path=`find ${oracinventory_path}/logs -type f -print| xargs -n 1 -i egrep -l "TOPLEVEL_COMPONENT.*9.2.0.8" {}` if [ -e "${oracle_install_log_path}" ]; then log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" else log_and_exit "ERROR" "Could not find an oracle install log file" -fi - - -test_pad() -{ - local file=$1 - sleep 5 - grep 'was successful' $file - res=$? - echo "result command value: $res" - if (( $res == 0 )); then - EXITCODE=0 - touch /var/opt/oracle/9.2.0.8_patchset_installed - log_and_exit "INFO" "You have installed 9.2.0.8 database server patch software" - else - log "INFO" "Not yet successful..." - fi - - return 1 -} - -while true; do - test_pad ${oracle_install_log_path} - sleep 5 +fi +test_pad() +{ +local file=$1 +sleep 5 +grep 'was successful' $file +if (( $? == 0 )); then + EXITCODE=0 + touch /var/opt/oracle/9.2.0.8_patchset_installed + log_and_exit "INFO" "You have installed 9.2.0.8 database server patch software" +else + log "INFO" "Not yet successful..." +fi +return 1 +} + +while true; do + test_pad ${oracle_install_log_path} + sleep 5 done - exit 0
jeremybaumont/Oracle-puppet-module
c257529e46d0ff8b81ffe4f1200109f0ef74ea4e
Add product directory in oracle home path
diff --git a/modules/oracle/manifests/directories.pp b/modules/oracle/manifests/directories.pp index fa3513e..bc614cf 100644 --- a/modules/oracle/manifests/directories.pp +++ b/modules/oracle/manifests/directories.pp @@ -1,505 +1,522 @@ # directories.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # puppet manages the following directories, they may not following OFA # but feel free to modify at your convenience # # ORACLE_BASE # /opt/app/oracle # # ORACLE_HOME # /opt/app/oracle/product/11.2.0/earth # # Inventory # /opt/app/oracle/oraInventory # # Data Directory # /ora06/dbsid/dbf/ # /ora07/dbsid/dbf/ # # Control Files # /ora01/dbsid/ctl # /ora02/dbsid/ctl # /ora03/dbsid/ctl # # Redo Logs # /ora01/dbsid/redo # /ora02/dbsid/redo # /ora03/dbsid/redo # # Archives # /ora04/dbsid/arch/ # # Dumps # /logs/oracle/diag/rdbms/db_name/db_sid/udump.... # # Flashback # /flash_recovery_area/dbsid # # RMAN # /rman-backup class oracle::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => false, mode => $mode } } # required directories oracle_dir { "var_opt": path => "/var/opt", ensure => directory, owner => "root", group => "root", before => File["var_opt_oracle"], mode => 755 } oracle_dir { "/logs": path => "/logs", ensure => directory, owner => "root", group => "root", mode => 755 } oracle_dir { "var_opt_oracle": path => "/var/opt/oracle", ensure => directory, owner => "oracle", group => "oinstall", require => File["var_opt"], mode => 755 } oracle_dir { "/opt/app": path => "/opt/app", ensure => directory, owner => "root", group => "root", before => File["oracle_base"], mode => 755 } $oracle_base_path = "/opt/app/oracle" $orainventory_path = "$oracle_base_path/oraInventory" file { "/var/opt/oracle/oraInst.loc": content => template("oracle/oraInst-template.erb"), ensure => present, force => true, owner => "oracle", group => "oinstall", mode => 644 } oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], - File["oracle_major_version"] + File["oracle_major_version"], + File["oracle_product"] ], require => File["/opt/app"], mode => 755 } + oracle_dir { + "oracle_product": + path => "${oracle_base_path}/product", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => File["oracle_base"], + before => [ + File["oracle_home"], + File["oracle_major_version"], + ], + } + oracle_dir { "oracle_major_version": - path => "${oracle_base_path}/${oracle_major_version}", + path => "${oracle_base_path}/product/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", - require => File["oracle_base"], + require => [ + File["oracle_base"], + File["oracle_product"] + ], before => [ File["oracle_home"], ], mode => 755 } - $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_patch_version}" + $oracle_home_path = "${oracle_base_path}/product/${oracle_major_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], ], mode => 755 } $oracle_ora01 = "/ora01" $oracle_ora02 = "/ora02" $oracle_ora03 = "/ora03" $oracle_ora04 = "/ora04" $oracle_ora06 = "/ora06" $oracle_ora07 = "/ora07" oracle_dir { "oracle_ora01": path => "${oracle_ora01}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora01_dbsid"], File["oracle_ora01_dbf"], ], mode => 755 } oracle_dir { "oracle_ora02": path => "${oracle_ora02}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora02_dbsid"], File["oracle_ora02_dbf"], ], mode => 755 } oracle_dir { "oracle_ora03": path => "${oracle_ora03}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora03_dbsid"], File["oracle_ora03_dbf"], ], mode => 755 } oracle_dir { "oracle_ora04": path => "${oracle_ora04}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora04_dbsid"], File["oracle_ora04_dbf"], ], mode => 755 } oracle_dir { "oracle_ora06": path => "${oracle_ora06}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora06_dbsid"], File["oracle_ora06_dbf"], ], mode => 755 } oracle_dir { "oracle_ora07": path => "${oracle_ora07}", ensure => directory, owner => "oracle", group => "dba", before => [ File["oracle_ora07_dbsid"], File["oracle_ora07_dbf"], ], mode => 755 } oracle_dir { "oracle_ora01_dbsid": path => "${oracle_ora01}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora01"], before => File["oracle_ora01_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora02_dbsid": path => "${oracle_ora02}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora02"], before => File["oracle_ora02_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora03_dbsid": path => "${oracle_ora03}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora03"], before => File["oracle_ora03_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora04_dbsid": path => "${oracle_ora04}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora04"], before => File["oracle_ora04_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora06_dbsid": path => "${oracle_ora06}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora06"], before => File["oracle_ora06_dbf"], group => "dba", mode => 755 } oracle_dir { "oracle_ora07_dbsid": path => "${oracle_ora07}/${oracle_sid}", ensure => directory, owner => "oracle", require => File["oracle_ora07"], before => File["oracle_ora07_dbf"], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_dbf": path => "${oracle_ora01}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_dbf": path => "${oracle_ora02}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_dbf": path => "${oracle_ora03}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora04_dbf": path => "${oracle_ora04}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora04"], File["oracle_ora04_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora06_dbf": path => "${oracle_ora06}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora06"], File["oracle_ora06_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora07_dbf": path => "${oracle_ora07}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", require => [ File["oracle_ora07"], File["oracle_ora07_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_ctl": path => "${oracle_ora01}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_ctl": path => "${oracle_ora02}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_ctl": path => "${oracle_ora03}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora01_redo": path => "${oracle_ora01}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora01"], File["oracle_ora01_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora02_redo": path => "${oracle_ora02}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora02"], File["oracle_ora02_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora03_redo": path => "${oracle_ora03}/${oracle_sid}/redo", ensure => directory, owner => "oracle", require => [ File["oracle_ora03"], File["oracle_ora03_dbsid"], ], group => "dba", mode => 755 } oracle_dir{ "oracle_ora04_arch": path => "${oracle_ora04}/${oracle_sid}/arch", ensure => directory, owner => "oracle", require => [ File["oracle_ora04"], File["oracle_ora04_dbsid"], ], group => "dba", mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755 } } # end of class oracle::directories
jeremybaumont/Oracle-puppet-module
dc3e5e9a2eb8a6c773356e9b45499132ac495466
Add stop/start virtual frame buffer
diff --git a/modules/oracle/files/users/oracle/bin/start_vfb.sh b/modules/oracle/files/users/oracle/bin/start_vfb.sh new file mode 100755 index 0000000..8aa9915 --- /dev/null +++ b/modules/oracle/files/users/oracle/bin/start_vfb.sh @@ -0,0 +1,32 @@ +#!/usr/bin/bash + +XSUN=/usr/openwin/bin/Xsun +DATE=`date '+%y%m%d.%H%M%S'` + +#Check XSUN is not running +# -> tbd +PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` +if [ "$PROC_PID" == "" ]; then + echo "XSUN Virtual Frame Buffer is not running" +else + echo "XSUN Virtual Frame Buffer is running. Please stop it first." + ps -fe | grep -v grep | grep $XSUN + exit 1 +fi + +#- Start the XSUN Virtual Frame Buffer +echo "Starting XSUN Virtual Frame Buffer" +nohup $XSUN :0 +nkeyboard +nmouse -dev vfb screen 0 1024x768x8 2>&1 1>/var/tmp/start_vfb.$DATE.out & +sleep 3 + +#Check XSUN Virtual Frame Buffer has started +# -> tbd +PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` +if [ "$PROC_PID" == "" ]; then + echo "XSUN Virtual Frame Buffer did not start successfully ;-(" + exit 1 +else + echo "XSUN Virtual Frame Buffer start successfully !" + ps -fe | grep -v grep | grep $XSUN +fi + diff --git a/modules/oracle/files/users/oracle/bin/stop_vfb.sh b/modules/oracle/files/users/oracle/bin/stop_vfb.sh new file mode 100755 index 0000000..6bb2a1f --- /dev/null +++ b/modules/oracle/files/users/oracle/bin/stop_vfb.sh @@ -0,0 +1,22 @@ +#!/usr/bin/bash + +XSUN=/usr/openwin/bin/Xsun +DATE=`date '+%y%m%d.%H%M%S'` + +#Check XSUN is not running +# -> tbd +PROC_PID=`ps -elf | grep -v grep | grep Xsun | awk '{ print $4}'` +if [ "$PROC_PID" == "" ]; then + echo "XSUN Virtual Frame Buffer is not running" +else + echo "XSUN Virtual Frame Buffer is running. Stoppin it ..." + kill -9 $PROC_PID > /var/tmp/stop_vfb_$DATE.out + if [ $? -eq 0 ]; then + echo "XSUN Virtual Frame Buffer stopped." + exit 0 + else + echo "XSUN Virtual Frame Buffer failed to be stopped ;-(" + exit 1 + fi + +fi diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp index 5317f13..3225838 100644 --- a/modules/oracle/manifests/software.pp +++ b/modules/oracle/manifests/software.pp @@ -1,162 +1,260 @@ # software.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::software { + # You need the software cd/dvd/disks from Oracle downloaded + # somewhere on the local machine $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { - default: {err("unknown oracle version value ${oracle_version}") } + default: {err("unknown oracle version value ${oracle_version} or not yet implemented") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" + + # start an x server, required for the + # oracle installer + exec { + "start_vfb": + command => "start_vfb.sh", + path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", + "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "/users/oracle/bin", + group => "root", + user => "root", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File["/users/oracle/bin/"], + File["/users/oracle/bin/start_vfb.sh"] + ], + timeout => "-1", + } + # build a script to run silent installer - # of 11.2.0.1 Disk 1 Oracle database + # of 9.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_9.2.0.1.sh": name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui": command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", - path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", + "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.1_installed", group => "oinstall", user => "oracle", - environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], + environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.1.sh"], + Exec ["start_vfb"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } + # before installing the 9.2.0.8 patchset + # we need to shutdown all processes + # using the oracle home directories + file { + "stop_oracle_home_proc.sh": + name => "${tmp_dir}/stop_oracle_home_proc.sh", + content => template("oracle/stop_oracle_home_proc.erb"), + mode => 755, + owner =>"oracle", + group => "oinstall", + + } + + exec { + "stop_oracle_home_proc": + command => "stop_oracle_home_proc.sh > ${tmp_dir}/stop_oracle_home_proc.log", + path => ["/usr/bin", + "/usr/sbin", + ".", + "/opt/csw/bin", + "/usr/sbin", + "/usr/bin", + "/usr/dt/bin", + "/usr/openwin/bin", + "/usr/ccs/bin", + "/usr/sfw/bin", + "/usr/perl5/5.8.4/bin", + "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + group => "dba", + user => "oracle", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + Exec ["runinstaller-oui"], + File ["stop_oracle_home_proc.sh"], + File["var_opt_oracle"], + File["oracle_home"], + File["oracle_base"], + File["/users/oracle/.bash_profile"], + File["/var/opt/oracle/oraInst.loc"], + File["/users/oracle/.bashrc"], + File["/users/oracle"], + User["oracle"], + Group["dba"], + Group["oinstall"] + ], + timeout => "-1", + + } + $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" # build a script to run silent installer # of 9.2.0.8 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_9.2.0.8_patchset.sh": name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.8 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui": command => "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.8_patchset_installed", group => "oinstall", user => "oracle", - environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], + environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.8_patchset.sh"], Exec ["runinstaller-oui"], + Exec ["stop_oracle_home_proc"], File["var_opt_oracle"], File["oracle_home"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } + # stop x server, required for the + # oracle installer + exec { + "stop_vfb": + command => "stop_vfb.sh", + path => ["/users/oracle/bin","/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", + "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "/users/oracle/bin", + group => "root", + user => "root", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File["/users/oracle/bin/"], + Exec["runinstaller-patchset-oui"], + File["/users/oracle/bin/stop_vfb.sh"] + ], + timeout => "-1", + } } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index be7f2a8..cd3dc9d 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,56 +1,72 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, uid => 4001, gid => "dba", groups => [ "oinstall" , "other" ], comment => "Oracle Application User", home => "/users/oracle", require => [ Group["dba"], Group["oinstall"] ] , shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": source => "puppet:/oracle/users/oracle/.bashrc", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": source => "puppet:/oracle/users/oracle/.bash_profile", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": source => "puppet:/oracle/users/oracle/.ssh/authorized_keys", ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": # source => "puppet:/oracle/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } + + # unix scripts + file { + "/users/oracle/bin/": + ensure => directory, + mode => 0750, owner => oracle, group => dba; + "/users/oracle/bin/start_vfb.sh": + source => "puppet:/oracle/users/oracle/bin/start_vfb.sh", + ensure => present, replace => true, + mode => 0755, owner => oracle, group => dba; + "/users/oracle/bin/stop_vfb.sh": + source => "puppet:/oracle/users/oracle/bin/stop_vfb.sh", + ensure => present, replace => true, + mode => 0755, owner => oracle, group => dba; + } + } diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index a24996d..261e86e 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,89 +1,79 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } # Display main environment variables inforacle() { log "INFO" "ORACLE_SID=${ORACLE_SID}" log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" log "INFO" "ORACLE_HOME=${ORACLE_HOME}" } # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> -# optional oracle unix environmen variables to simplify code review -ORACLE_DUMPS=<%= oracle_dumps %> -ORACLE_ORALOGS=<%= oracle_oralogs %> export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID # update lib path and command path -export PATH=$ORACLE_HOME/bin:$PATH +export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$HOME/bin:$PATH export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH # oracle alias to speed up productivity -alias alert='$HOME/dba_alertlog ${ORACLE_DUMPS}/$ORACLE_SID/bdump/alert_$ORACLE_SID.log | tail -200 | less' -alias arch='cd ${ORACLE_ORALOGS}/$ORACLE_SID/arch && ls -lrt' -alias bdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/bdump && ls -lrt' -alias udump='cd ${ORACLE_DUMPS}/$ORACLE_SID/udump && ls -lrt' -alias cdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/cdump && ls -lrt' -alias adump='cd ${ORACLE_DUMPS}/$ORACLE_SID/adump && ls -lrt' -alias pfile='cd ${ORACLE_DUMPS}/$ORACLE_SID/pfile && ls -lrt' alias rm='rm -i' alias sid='env|grep ORACLE_SID' alias i='inforacle' # display oracle main environment at login inforacle # set up X display and term for screen # kind of magic here but the silent installer need # to make an x connection in order to load oui java classes -DISPLAY=p-reduck.euronet.nl:0.0 +DISPLAY=:0.0 TERM=vt220 export DISPLAY TERM # keyboard commands stty erase set -o vi diff --git a/modules/oracle/templates/stop_oracle_home_proc.erb b/modules/oracle/templates/stop_oracle_home_proc.erb new file mode 100644 index 0000000..8034207 --- /dev/null +++ b/modules/oracle/templates/stop_oracle_home_proc.erb @@ -0,0 +1,38 @@ +#!/usr/bin/bash + +EXITCODE=1 + +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + +log "INFO" "Stopping processes using the oracle home directories." + + +cd <%= current_oracle_home %>/Apache/Apache/bin/ +./apachectl stop + +cd <%= current_oracle_home %>/bin/ +,/tnslsnr stop + +log "INFO" "Processes using the oracle home directories should be stop" + + +exit 0
jeremybaumont/Oracle-puppet-module
02e3860c8c451461080c634517b2bd12d9962b7d
change oracle directories resources
diff --git a/modules/oracle/manifests/directories.pp b/modules/oracle/manifests/directories.pp index aab6144..fa3513e 100644 --- a/modules/oracle/manifests/directories.pp +++ b/modules/oracle/manifests/directories.pp @@ -1,358 +1,505 @@ # directories.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # + + +# puppet manages the following directories, they may not following OFA +# but feel free to modify at your convenience +# +# ORACLE_BASE +# /opt/app/oracle +# +# ORACLE_HOME +# /opt/app/oracle/product/11.2.0/earth +# +# Inventory +# /opt/app/oracle/oraInventory +# +# Data Directory +# /ora06/dbsid/dbf/ +# /ora07/dbsid/dbf/ +# +# Control Files +# /ora01/dbsid/ctl +# /ora02/dbsid/ctl +# /ora03/dbsid/ctl +# +# Redo Logs +# /ora01/dbsid/redo +# /ora02/dbsid/redo +# /ora03/dbsid/redo +# +# Archives +# /ora04/dbsid/arch/ +# +# Dumps +# /logs/oracle/diag/rdbms/db_name/db_sid/udump.... +# +# Flashback +# /flash_recovery_area/dbsid +# +# RMAN +# /rman-backup + class oracle::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => false, mode => $mode } } # required directories oracle_dir { "var_opt": path => "/var/opt", ensure => directory, owner => "root", group => "root", before => File["var_opt_oracle"], mode => 755 } oracle_dir { "/logs": path => "/logs", ensure => directory, owner => "root", group => "root", - before => File["oracle_logs"], mode => 755 } - oracle_dir { - "/data": - path => "/data", - ensure => directory, - owner => "root", - group => "root", - before => File["oracle_data"], - mode => 755 - } oracle_dir { "var_opt_oracle": path => "/var/opt/oracle", ensure => directory, owner => "oracle", group => "oinstall", require => File["var_opt"], mode => 755 } oracle_dir { - "/opt/applications": - path => "/opt/applications", + "/opt/app": + path => "/opt/app", ensure => directory, owner => "root", group => "root", before => File["oracle_base"], mode => 755 } - $oracle_base_path = "/opt/applications/oracle" + $oracle_base_path = "/opt/app/oracle" $orainventory_path = "$oracle_base_path/oraInventory" file { "/var/opt/oracle/oraInst.loc": content => template("oracle/oraInst-template.erb"), ensure => present, force => true, owner => "oracle", group => "oinstall", mode => 644 } oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], - File["oracle_major_version"], - File["oracle_version"] + File["oracle_major_version"] ], - require => File["/opt/applications"], + require => File["/opt/app"], mode => 755 } -# $oracle_inventory_path = "${oracle_base_path}/oraInventory" -# oracle_dir { -# "oracle_inventory": -# path => $oracle_inventory_path, -# ensure => directory, -# owner => "oracle", -# group => "oinstall", -# mode => 775 -# } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], - File["oracle_version"] ], mode => 755 } - oracle_dir { - "oracle_version": - path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", - ensure => directory, - owner => "oracle", - group => "oinstall", - require => [ - File["oracle_base"], - File["oracle_major_version"] - ], - before => File["oracle_home"] , - mode => 755 - } - $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" + $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], - File["oracle_version"] ], mode => 755 } + + $oracle_ora01 = "/ora01" + $oracle_ora02 = "/ora02" + $oracle_ora03 = "/ora03" + $oracle_ora04 = "/ora04" + $oracle_ora06 = "/ora06" + $oracle_ora07 = "/ora07" + oracle_dir { - "oracle_data": - path => "/data/oracle", + "oracle_ora01": + path => "${oracle_ora01}", ensure => directory, owner => "oracle", group => "dba", - require => File["/data"], + before => [ + File["oracle_ora01_dbsid"], + File["oracle_ora01_dbf"], + ], mode => 755 - } - - $oracle_oralogs = "/data/oracle/oralogs" + } + oracle_dir { - "oracle_oralogs": - path => "${oracle_oralogs}", + "oracle_ora02": + path => "${oracle_ora02}", ensure => directory, owner => "oracle", group => "dba", - require => File["oracle_data"], + before => [ + File["oracle_ora02_dbsid"], + File["oracle_ora02_dbf"], + ], mode => 755 - } + } oracle_dir { - "oracle_oralogs_${oracle_sid}": - path => "${oracle_oralogs}/${oracle_sid}", + "oracle_ora03": + path => "${oracle_ora03}", ensure => directory, owner => "oracle", group => "dba", - require => File["oracle_oralogs"], before => [ - File["oracle_oralogs_redo"], - File["oracle_oralogs_ctl"], - File["oracle_oralogs_arch"] - ], + File["oracle_ora03_dbsid"], + File["oracle_ora03_dbf"], + ], mode => 755 - } + } + + oracle_dir { + "oracle_ora04": + path => "${oracle_ora04}", + ensure => directory, + owner => "oracle", + group => "dba", + before => [ + File["oracle_ora04_dbsid"], + File["oracle_ora04_dbf"], + ], + mode => 755 + } + + oracle_dir { + "oracle_ora06": + path => "${oracle_ora06}", + ensure => directory, + owner => "oracle", + group => "dba", + before => [ + File["oracle_ora06_dbsid"], + File["oracle_ora06_dbf"], + ], + mode => 755 + } + + oracle_dir { + "oracle_ora07": + path => "${oracle_ora07}", + ensure => directory, + owner => "oracle", + group => "dba", + before => [ + File["oracle_ora07_dbsid"], + File["oracle_ora07_dbf"], + ], + mode => 755 + } + + + oracle_dir { + "oracle_ora01_dbsid": + path => "${oracle_ora01}/${oracle_sid}", + ensure => directory, + owner => "oracle", + require => File["oracle_ora01"], + before => File["oracle_ora01_dbf"], + group => "dba", + mode => 755 + } + + oracle_dir { + "oracle_ora02_dbsid": + path => "${oracle_ora02}/${oracle_sid}", + ensure => directory, + owner => "oracle", + require => File["oracle_ora02"], + before => File["oracle_ora02_dbf"], + group => "dba", + mode => 755 + } + + oracle_dir { + "oracle_ora03_dbsid": + path => "${oracle_ora03}/${oracle_sid}", + ensure => directory, + owner => "oracle", + require => File["oracle_ora03"], + before => File["oracle_ora03_dbf"], + group => "dba", + mode => 755 + } + + oracle_dir { + "oracle_ora04_dbsid": + path => "${oracle_ora04}/${oracle_sid}", + ensure => directory, + owner => "oracle", + require => File["oracle_ora04"], + before => File["oracle_ora04_dbf"], + group => "dba", + mode => 755 + } + + oracle_dir { + "oracle_ora06_dbsid": + path => "${oracle_ora06}/${oracle_sid}", + ensure => directory, + owner => "oracle", + require => File["oracle_ora06"], + before => File["oracle_ora06_dbf"], + group => "dba", + mode => 755 + } + + oracle_dir { + "oracle_ora07_dbsid": + path => "${oracle_ora07}/${oracle_sid}", + ensure => directory, + owner => "oracle", + require => File["oracle_ora07"], + before => File["oracle_ora07_dbf"], + group => "dba", + mode => 755 + } oracle_dir{ - "oracle_oralogs_redo": - path => "${oracle_oralogs}/${oracle_sid}/redo", + "oracle_ora01_dbf": + path => "${oracle_ora01}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora01"], + File["oracle_ora01_dbsid"], + ], group => "dba", - require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ - "oracle_oralogs_ctl": - path => "${oracle_oralogs}/${oracle_sid}/ctl", + "oracle_ora02_dbf": + path => "${oracle_ora02}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora02"], + File["oracle_ora02_dbsid"], + ], group => "dba", - require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ - "oracle_oralogs_arch": - path => "${oracle_oralogs}/${oracle_sid}/arch", + "oracle_ora03_dbf": + path => "${oracle_ora03}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora03"], + File["oracle_ora03_dbsid"], + ], group => "dba", - require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } - oracle_dir { - "oracle_oradata": - path => "/data/oracle/oradata", + + oracle_dir{ + "oracle_ora04_dbf": + path => "${oracle_ora04}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora04"], + File["oracle_ora04_dbsid"], + ], group => "dba", - require => File["oracle_data"], - before => File["oracle_oradata_${oracle_sid}"], mode => 755 } - oracle_dir { - "oracle_oradata_${oracle_sid}": - path => "/data/oracle/oradata/${oracle_sid}", + oracle_dir{ + "oracle_ora06_dbf": + path => "${oracle_ora06}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora06"], + File["oracle_ora06_dbsid"], + ], group => "dba", - require => File["oracle_oradata"], mode => 755 - } - $oracle_logs = "/logs/oracle" - oracle_dir { - "oracle_logs": - path => "${oracle_logs}", + oracle_dir{ + "oracle_ora07_dbf": + path => "${oracle_ora07}/${oracle_sid}/dbf", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora07"], + File["oracle_ora07_dbsid"], + ], group => "dba", - require => File["/logs"], - mode => 755, - before => [ - File["oracle_dumps"], - File["oracle_user_dumps"], - File["oracle_background_dumps"], - File["oracle_audit_dumps"], - File["oracle_core_dumps"] - ] + mode => 755 } - $oracle_dumps = "${oracle_logs}/oradumps" - oracle_dir { - "oracle_dumps": - path => "${oracle_dumps}", + oracle_dir{ + "oracle_ora01_ctl": + path => "${oracle_ora01}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora01"], + File["oracle_ora01_dbsid"], + ], group => "dba", - require => File["oracle_logs"], - before => [ - File["oracle_user_dumps"], - File["oracle_background_dumps"], - File["oracle_audit_dumps"], - File["oracle_core_dumps"], - File["oracle_pfile_dir"], - File["oracle_dumps_${oracle_sid}"] - ] , mode => 755 } - oracle_dir { - "oracle_dumps_${oracle_sid}": - path => "/logs/oracle/oradumps/${oracle_sid}", + oracle_dir{ + "oracle_ora02_ctl": + path => "${oracle_ora02}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora02"], + File["oracle_ora02_dbsid"], + ], group => "dba", - require => File["oracle_dumps"], - before => [ - File["oracle_user_dumps"], - File["oracle_background_dumps"], - File["oracle_audit_dumps"], - File["oracle_core_dumps"], - File["oracle_pfile_dir"] + mode => 755 + } + + oracle_dir{ + "oracle_ora03_ctl": + path => "${oracle_ora03}/${oracle_sid}/ctl", + ensure => directory, + owner => "oracle", + require => [ + File["oracle_ora03"], + File["oracle_ora03_dbsid"], ], - mode => 755 + group => "dba", + mode => 755 } - oracle_dir { - "oracle_user_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/udump", + oracle_dir{ + "oracle_ora01_redo": + path => "${oracle_ora01}/${oracle_sid}/redo", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora01"], + File["oracle_ora01_dbsid"], + ], group => "dba", - require => File["oracle_dumps_${oracle_sid}"], mode => 755 } - oracle_dir { - "oracle_background_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/bdump", + oracle_dir{ + "oracle_ora02_redo": + path => "${oracle_ora02}/${oracle_sid}/redo", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora02"], + File["oracle_ora02_dbsid"], + ], group => "dba", - require => File["oracle_dumps_${oracle_sid}"], mode => 755 } - oracle_dir { - "oracle_audit_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/adump", + oracle_dir{ + "oracle_ora03_redo": + path => "${oracle_ora03}/${oracle_sid}/redo", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora03"], + File["oracle_ora03_dbsid"], + ], group => "dba", - require => File["oracle_dumps_${oracle_sid}"], mode => 755 } - - oracle_dir { - "oracle_core_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/cdump", + + oracle_dir{ + "oracle_ora04_arch": + path => "${oracle_ora04}/${oracle_sid}/arch", ensure => directory, owner => "oracle", + require => [ + File["oracle_ora04"], + File["oracle_ora04_dbsid"], + ], group => "dba", - require => File["oracle_dumps_${oracle_sid}"], mode => 755 } + $oracle_logs = "/logs/oracle" oracle_dir { - "oracle_pfile_dir": - path => "/logs/oracle/oradumps/${oracle_sid}/pfile", + "oracle_logs": + path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", - require => File["oracle_dumps_${oracle_sid}"], + require => File["/logs"], mode => 755 } } # end of class oracle::directories diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp index 33409b2..5317f13 100644 --- a/modules/oracle/manifests/software.pp +++ b/modules/oracle/manifests/software.pp @@ -1,166 +1,162 @@ # software.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::software { $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version}") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # build a script to run silent installer # of 11.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_9.2.0.1.sh": name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui": command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.1_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.1.sh"], File["var_opt_oracle"], File["oracle_home"], - File["oracle_version"], - File["oracle_major_version"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" # build a script to run silent installer # of 9.2.0.8 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_9.2.0.8_patchset.sh": name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.8 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui": command => "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.8_patchset_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ File ["wruninstaller_9.2.0.8_patchset.sh"], Exec ["runinstaller-oui"], File["var_opt_oracle"], File["oracle_home"], - File["oracle_version"], - File["oracle_major_version"], File["oracle_base"], File["/users/oracle/.bash_profile"], File["/var/opt/oracle/oraInst.loc"], File["/users/oracle/.bashrc"], File["/users/oracle"], User["oracle"], Group["dba"], Group["oinstall"] ], timeout => "-1", } } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } }
jeremybaumont/Oracle-puppet-module
afc026af8b49c94106c0169d967b36ec3db82345
Fixed oracle files from filebucket to module
diff --git a/manifests/nodes.pp b/manifests/nodes.pp index 7c1a688..4ad389a 100644 --- a/manifests/nodes.pp +++ b/manifests/nodes.pp @@ -1,28 +1,40 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # node 'jeremy-test.wanadoo.nl' { $architecture = "sparc32" $operatingsystem = "solaris" $oracle_major_version = "9i" $oracle_version = "9.2.0.8" $oracle_patch_version = "earth" $oracle_sid = "PLGRND" include oracle::database_server } + +node 'test1.wanadoo.nl' { + $architecture = "sparc32" + $operatingsystem = "solaris" + + $oracle_major_version = "9i" + $oracle_version = "9.2.0.8" + $oracle_patch_version = "earth" + $oracle_sid = "PLGRND" + + include oracle::database_server +} diff --git a/files/users/oracle/.bash_profile b/modules/oracle/files/users/oracle/.bash_profile similarity index 100% rename from files/users/oracle/.bash_profile rename to modules/oracle/files/users/oracle/.bash_profile diff --git a/files/users/oracle/.bashrc b/modules/oracle/files/users/oracle/.bashrc similarity index 100% rename from files/users/oracle/.bashrc rename to modules/oracle/files/users/oracle/.bashrc diff --git a/files/users/oracle/.ssh/authorized_keys b/modules/oracle/files/users/oracle/.ssh/authorized_keys similarity index 100% rename from files/users/oracle/.ssh/authorized_keys rename to modules/oracle/files/users/oracle/.ssh/authorized_keys diff --git a/modules/oracle/manifests/system_packages.pp b/modules/oracle/manifests/system_packages.pp index 5b357a6..bed9217 100644 --- a/modules/oracle/manifests/system_packages.pp +++ b/modules/oracle/manifests/system_packages.pp @@ -1,70 +1,70 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("INFO - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("INFO - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("INFO - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } } notify {"INFO - the operating system is ${operatingsystem}": } notify {"INFO - the architecture is ${architecture}": } notify {"INFO - the architecture is ${oracle_major_version}": } notify {"INFO - the list of packages required is ${system_packages}": } - package { $ystem_packages: ensure => installed, provider => $sun_provider } + package { $system_packages: ensure => installed, provider => $sun_provider } }# end of class oracle::system_packages diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index 2decef5..be7f2a8 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,56 +1,56 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, uid => 4001, gid => "dba", groups => [ "oinstall" , "other" ], comment => "Oracle Application User", home => "/users/oracle", require => [ Group["dba"], Group["oinstall"] ] , shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": - source => "$fileserver/users/oracle/.bashrc", + source => "puppet:/oracle/users/oracle/.bashrc", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": - source => "$fileserver/users/oracle/.bash_profile", + source => "puppet:/oracle/users/oracle/.bash_profile", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": - source => "$fileserver/users/oracle/.ssh/authorized_keys", + source => "puppet:/oracle/users/oracle/.ssh/authorized_keys", ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": -# source => "$fileserver/users/oracle/.ssh/config", +# source => "puppet:/oracle/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } }
jeremybaumont/Oracle-puppet-module
e24df5de96752f56fd32ab537fac53c59d84b2e2
Fixed DSL graph dependencies and wrapper scripts
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 3397a8a..1a05752 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,23 +1,21 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server inherits -oracle::server::database::enterprise { - - + oracle::server::database::enterprise { } # end of class oracle::database_server diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp index b130c62..33409b2 100644 --- a/modules/oracle/manifests/software.pp +++ b/modules/oracle/manifests/software.pp @@ -1,140 +1,166 @@ # software.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::software { $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version}") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" $tmp_dir = "/var/tmp" # build a script to run silent installer # of 11.2.0.1 Disk 1 Oracle database # server software enterprise edition file{ "wruninstaller_9.2.0.1.sh": name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.1 Disk 1 # Orable database server software # enterprise edition exec { "runinstaller-oui": command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.1_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], - require => File ["wruninstaller_9.2.0.1.sh"], + require => [ + File ["wruninstaller_9.2.0.1.sh"], + File["var_opt_oracle"], + File["oracle_home"], + File["oracle_version"], + File["oracle_major_version"], + File["oracle_base"], + File["/users/oracle/.bash_profile"], + File["/var/opt/oracle/oraInst.loc"], + File["/users/oracle/.bashrc"], + File["/users/oracle"], + User["oracle"], + Group["dba"], + Group["oinstall"] + ], timeout => "-1", } $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" # build a script to run silent installer # of 9.2.0.8 Disk 1 Oracle database # server software enterprise edition # patchset file{ "wruninstaller_9.2.0.8_patchset.sh": name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } # run silent installer of 9.2.0.8 Disk 1 # Orable database server software # enterprise edition patchset exec { "runinstaller-patchset-oui": command => "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${tmp_dir}", creates => "/var/opt/oracle/9.2.0.8_patchset_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => [ - File ["wruninstaller_9.2.0.8_patchset.sh"], - Exec ["runinstaller-oui"] + File ["wruninstaller_9.2.0.8_patchset.sh"], + Exec ["runinstaller-oui"], + File["var_opt_oracle"], + File["oracle_home"], + File["oracle_version"], + File["oracle_major_version"], + File["oracle_base"], + File["/users/oracle/.bash_profile"], + File["/var/opt/oracle/oraInst.loc"], + File["/users/oracle/.bashrc"], + File["/users/oracle"], + User["oracle"], + Group["dba"], + Group["oinstall"] ], timeout => "-1", } } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index a433363..2decef5 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,56 +1,56 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, - uid => 4000, + uid => 4001, gid => "dba", groups => [ "oinstall" , "other" ], comment => "Oracle Application User", home => "/users/oracle", require => [ Group["dba"], Group["oinstall"] ] , shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": source => "$fileserver/users/oracle/.bashrc", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": source => "$fileserver/users/oracle/.bash_profile", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": source => "$fileserver/users/oracle/.ssh/authorized_keys", ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": # source => "$fileserver/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } } diff --git a/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb index 9d1920b..7d254f1 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb @@ -1,60 +1,71 @@ #!/usr/bin/bash +EXITCODE=1 -echo " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"<%= disk2_9201_path %>\" LOCATION_FOR_DISK3=\"<%= disk3_9201_path %>\" s_cfgtyperet=\"Software Only\" " +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + +log "INFO" " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"<%= disk2_9201_path %>\" LOCATION_FOR_DISK3=\"<%= disk3_9201_path %>\" s_cfgtyperet=\"Software Only\" " cd <%= disk1_9201_path %> +log "INFO" "Current wokring directory: `pwd`" +log "INFO" "The runinstaller is starting..." ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" LOCATION_FOR_DISK2="<%= disk2_9201_path %>" LOCATION_FOR_DISK3="<%= disk3_9201_path %>" s_cfgtyperet="Software Only" +log "INFO" "The runinstaller is started..." + +sleep 120 orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" +#oracle_install_log_path=`find ${oracinventory_path}/logs -type f -print| xargs -n 1 -i egrep -l "TOPLEVEL_COMPONENT.*9.2.0.1" {}` + + +if [ -e "${oracle_install_log_path}" ]; then + log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" +else + log_and_exit "ERROR" "Could not find an oracle install log file" +fi -function test_pad() -{ - file=$1 - sleep 120 +test_pad() +{ + local file=$1 + sleep 5 grep 'was successful' $file - if [ $? -eq 1 ]; then return 0; fi - - return 1 -} - - -function reverse() -{ - string=$1 - len=$(echo -n $string | wc -c) - while test $len -gt 0 - do - rev=$rev$(echo $string | cut -c $len) - len=$(( len - 1 )) - done - echo $rev -} - -ANIM="//--\\||" -PAD=" " -SLEEP="0.1" - -ANIM_L="$(reverse $ANIM)" -PAD_LN=${#PAD} -ANIM_LN=${#ANIM} -u=0; re=0; l=0 - -echo "Parsing log: ${oracle_install_log_path} for successful install message..." -while test_pad $oracle_install_log_path; do - if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi - if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi - echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" - if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi - u=$(( u + 1 )); l=$(( l + 1 )) - if [ $l -eq $ANIM_LN ]; then l=0; fi - sleep $SLEEP - echo "Parsing log and sleeping $SLEEP..." + if (( $? == 0 )); then + touch /var/opt/oracle/9.2.0.1_installed + EXITCODE=0 + log_and_exit "INFO" "You have installed 9.2.0.1 database server software" + else + log "INFO" "Not yet successful..." + fi + + return 1 +} + +while true; do + test_pad ${oracle_install_log_path} + sleep 5 done -touch /var/opt/oracle/9.2.0.1_installed -echo "The installation of Oracle9i 9.2.0.1 Database was successful." + exit 0 diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb index bbe9986..0c049b5 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb @@ -1,59 +1,100 @@ #!/usr/bin/bash +EXITCODE=1 -echo " Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" " +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + +sleep 90 + +log "INFO" "Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" " cd <%= disk1_9208_patchset_path %> +log "INFO" "Current wokring directory: `pwd`" + +log "INFO" "Stopping running processes in oracle home..." +kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep applications | grep -v grep |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +if [ $? -eq 0 ]; then + log "INFO" "Running processes in oracle home stopped !" +else + log_and_exit "ERROR" "Could not stopped running processes in oracle home properly: ${kill_isqlplus_cmd}" +fi + +log "INFO" "Stopping isqlplus..." +kill_isqlplus_cmd=`/usr/ucb/ps wwwaux | grep applications | grep isqlplus |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +if [ $? -eq 0 ]; then + log "INFO" "isqlplus stopped !" +else + log_and_exit "ERROR" "Could not stopped isqlplus properly: ${kill_isqlplus_cmd}" +fi +log "INFO" "Stopping oracle httpd server..." +$ORACLE_HOME/Apache/Apache/bin/apachectl stop +kill_httpd_cmd=`/usr/ucb/ps wwwaux | grep applications | grep httpd |awk '{print $2}' |xargs -n 1 -i kill -9 {}` +if [ $? -eq 0 ]; then + log "INFO" "httpd stopped !" +else + log_and_exit "ERROR" "Could not stopped httpd properly: ${kill_httpd_cmd}" +fi + + +log "INFO" "The runinstaller is starting..." ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" +log "INFO" "The runinstaller is started..." +sleep 120 orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" +#oracle_install_log_path=`find ${oracinventory_path}/logs -type f -print| xargs -n 1 -i egrep -l "TOPLEVEL_COMPONENT.*9.2.0.8" {}` + -function test_pad() -{ - file=$1 - - sleep 120 - grep 'was successful' $file - if [ $? -eq 1 ]; then return 0; fi - - return 1 -} - - -function reverse() -{ - string=$1 - len=$(echo -n $string | wc -c) - while test $len -gt 0 - do - rev=$rev$(echo $string | cut -c $len) - len=$(( len - 1 )) - done - echo $rev -} - -ANIM="//--\\||" -PAD=" " -SLEEP="0.1" - -ANIM_L="$(reverse $ANIM)" -PAD_LN=${#PAD} -ANIM_LN=${#ANIM} -u=0; re=0; l=0 - -echo "Parsing log: ${oracle_install_log_path} for successful install message..." -while test_pad $oracle_install_log_path; do - if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi - if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi - echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" - if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi - u=$(( u + 1 )); l=$(( l + 1 )) - if [ $l -eq $ANIM_LN ]; then l=0; fi - sleep $SLEEP -done -touch /var/opt/oracle/9.2.0.8_patchset_installed -echo "The installation of Oracle9i patchset 9.2.0.8 Database was successful." -exit 0 +if [ -e "${oracle_install_log_path}" ]; then + log "INFO" "Found an oracle install log file: ${oracle_install_log_path}" +else + log_and_exit "ERROR" "Could not find an oracle install log file" +fi + + +test_pad() +{ + local file=$1 + sleep 5 + grep 'was successful' $file + res=$? + echo "result command value: $res" + if (( $res == 0 )); then + EXITCODE=0 + touch /var/opt/oracle/9.2.0.8_patchset_installed + log_and_exit "INFO" "You have installed 9.2.0.8 database server patch software" + else + log "INFO" "Not yet successful..." + fi + + return 1 +} + +while true; do + test_pad ${oracle_install_log_path} + sleep 5 +done + +exit 0
jeremybaumont/Oracle-puppet-module
d0d0df04724629bf760bdfad0d81ee8c7483cae3
Corrected include class ordering
diff --git a/manifests/nodes.pp b/manifests/nodes.pp index fcff523..7c1a688 100644 --- a/manifests/nodes.pp +++ b/manifests/nodes.pp @@ -1,28 +1,28 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # -node 'jeremy-test.wanadoo.nl' inherits oracle_database_server { +node 'jeremy-test.wanadoo.nl' { $architecture = "sparc32" $operatingsystem = "solaris" $oracle_major_version = "9i" $oracle_version = "9.2.0.8" $oracle_patch_version = "earth" $oracle_sid = "PLGRND" include oracle::database_server } diff --git a/manifests/templates.pp b/manifests/templates.pp index cccd167..86c2053 100644 --- a/manifests/templates.pp +++ b/manifests/templates.pp @@ -1,29 +1,41 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # node basenode { case $operatingsystem { solaris: { include solaris } default: { include solaris } } include baseapps } node default inherits basenode{} -node oracle_database_server inherits basenode { + +node oracle_basenode { + include oracle::administrators + include oracle::system_packages +} + +node oracle_server inherits oracle_basenode { + include oracle::directories + include oracle::system_profile +} + +node oracle_database_server inherits oracle_server { + include oracle::software } diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index cefa4f5..3397a8a 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,567 +1,23 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # -class oracle::database_server { +class oracle::database_server inherits +oracle::server::database::enterprise { - # required user and groups - include oracle::administrators - - # required packages - include oracle::database_server::system_packages - - # required directories - include oracle::database_server::directories - - # required system profile - include oracle::database_server::system_profile - - # required oracle software - include oracle::database_server::software } # end of class oracle::database_server -### -### software class is responsible to silent install from a response file -### database server enterprise software only -### -class oracle::database_server::software { - - $oracle_base_software = "/opt/applications/repository/oracle/database_server" - - define install_oracle_database_server_software($oracle_version) { - case $operatingsystem { - default: { err ("unknown operation system value ${operatingsystem}") } - solaris: { - case $oracle_version { - default: {err("unknown oracle version value ${oracle_version}") } - "9.2.0.8": { - $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" - $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" - $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" - $current_oracle_home = $oracle::database_server::directories::oracle_home_path - $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" - $current_oracle_base = $oracle::database_server::directories::oracle_base_path - $orainventory_path = "$current_oracle_base/oraInventory" - - # build a script to run silent installer - # of 11.2.0.1 Disk 1 Oracle database - # server software enterprise edition - file{ - "wruninstaller_9.2.0.1.sh": - name => "${disk1_9201_path}/wruninstaller_9.2.0.1.sh", - content => template("oracle/wruninstaller_9.2.0.1-template.erb"), - mode => 755, - owner => "oracle", - group => "oinstall", - } - - # run silent installer of 9.2.0.1 Disk 1 - # Orable database server software - # enterprise edition - exec { - "runinstaller-oui": - command => "wruninstaller_9.2.0.1.sh >/var/tmp/runinstaller-oui_9.2.0.1.log", - path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], - cwd => "${disk1_9201_path}", - creates => "/var/opt/oracle/9.2.0.1_installed", - group => "oinstall", - user => "oracle", - environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], - logoutput => true, - returns => [0,1], - require => File ["wruninstaller_9.2.0.1.sh"], - timeout => "-1", - } - - - $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" - $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" - $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" - - # build a script to run silent installer - # of 9.2.0.8 Disk 1 Oracle database - # server software enterprise edition - # patchset - file{ - "wruninstaller_9.2.0.8_patchset.sh": - name => "${disk1_9208_patchset_path}/wruninstaller_9.2.0.8_patchset.sh", - content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), - mode => 755, - owner => "oracle", - group => "oinstall", - } - - # run silent installer of 9.2.0.8 Disk 1 - # Orable database server software - # enterprise edition patchset - exec { - "runinstaller-patchset-oui": - command => - "wruninstaller_9.2.0.8_patchset.sh >/var/tmp/runinstaller-patchset-oui_9.2.0.8.log", - path => ["/usr/bin", - "/usr/sbin", - ".", - "/opt/csw/bin", - "/usr/sbin", - "/usr/bin", - "/usr/dt/bin", - "/usr/openwin/bin", - "/usr/ccs/bin", - "/usr/sfw/bin", - "/usr/perl5/5.8.4/bin", - "/opt/SUNWspro/bin"], - cwd => "${disk1_9208_patchset_path}", - creates => "/var/opt/oracle/9.2.0.8_patchset_installed", - group => "oinstall", - user => "oracle", - environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], - logoutput => true, - returns => [0,1], - require => [ - File ["wruninstaller_9.2.0.8_patchset.sh"], - Exec ["runinstaller-oui"] - ], - timeout => "-1", - } - - - } - "10.2.0.4": { - - - } - } - } - } - } - - install_oracle_database_server_software { - "oracle database enterprise software": - oracle_version => $oracle_version, - } -} - - -### -### system_profile class is responsible to set up the correct operating -### system profile that is build from a template and inherit variables. -### The system profile will export the famous ORACLE_HOME, -### ORACLE_SID, ... and else environment variables. -### -class oracle::database_server::system_profile { - - - define oracle_system_profile ($oracle_base_path, $oracle_version, - $oracle_home_path, $oracle_sid, - $oracle_dumps, $oracle_oralogs) { - file { - $name: - content => template("oracle/bash_profile.oracle-template.erb"), - mode => 0644, owner => oracle, group => dba - } - } - - oracle_system_profile { - "/users/oracle/.bash_profile.oracle": - oracle_base_path => - $oracle::database_server::directories::oracle_base_path, - oracle_version => - $oracle::database_server::directories::oracle_version, oracle_home_path => - $oracle::database_server::directories::oracle_home_path, - oracle_sid => - $oracle::database_server::directories::oracle_sid, oracle_dumps => - $oracle::database_server::directories::oracle_dumps, - oracle_oralogs => - $oracle::database_server::directories::oracle_oralogs - } -} # end of class oracle::database_server::system_profile - -### -### -### -### -class oracle::database_server::directories { - - - define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { - file { - $name: - path => $path, - ensure => $ensure, - force => true, - owner => $owner, - group => $group, - recurse => false, - mode => $mode - } - } - - - # required directories - oracle_dir { - "var_opt": - path => "/var/opt", - ensure => directory, - owner => "root", - group => "root", - before => File["var_opt_oracle"], - mode => 755 - } - - oracle_dir { - "var_opt_oracle": - path => "/var/opt/oracle", - ensure => directory, - owner => "oracle", - group => "oinstall", - require => File["var_opt"], - mode => 755 - } - - $oracle_base_path = "/opt/applications/oracle" - $orainventory_path = "$oracle_base_path/oraInventory" - file { - "/var/opt/oracle/oraInst.loc": - content => template("oracle/oraInst-template.erb"), - ensure => present, - force => true, - owner => "oracle", - group => "oinstall", - mode => 644 - } - - oracle_dir { - "oracle_base": - path => $oracle_base_path, - ensure => directory, - owner => "oracle", - group => "oinstall", - before => [ - File["oracle_home"], - File["oracle_major_version"], - File["oracle_version"] - ], - require => File["/opt/applications"], - mode => 755 - } - -# $oracle_inventory_path = "${oracle_base_path}/oraInventory" -# oracle_dir { -# "oracle_inventory": -# path => $oracle_inventory_path, -# ensure => directory, -# owner => "oracle", -# group => "oinstall", -# mode => 775 -# } - - oracle_dir { - "oracle_major_version": - path => "${oracle_base_path}/${oracle_major_version}", - ensure => directory, - owner => "oracle", - group => "oinstall", - require => File["oracle_base"], - before => [ - File["oracle_home"], - File["oracle_version"] - ], - mode => 755 - } - - oracle_dir { - "oracle_version": - path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", - ensure => directory, - owner => "oracle", - group => "oinstall", - require => [ - File["oracle_base"], - File["oracle_major_version"] - ], - before => File["oracle_home"] , - mode => 755 - } - - $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" - oracle_dir { - "oracle_home": - path => "${oracle_home_path}", - ensure => directory, - owner => "oracle", - group => "oinstall", - require => [ - File["oracle_base"], - File["oracle_major_version"], - File["oracle_version"] - ], - mode => 755 - } - - oracle_dir { - "oracle_data": - path => "/data/oracle", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["/data"], - mode => 755 - } - - $oracle_oralogs = "/data/oracle/oralogs" - oracle_dir { - "oracle_oralogs": - path => "${oracle_oralogs}", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_data"], - mode => 755 - } - - oracle_dir { - "oracle_oralogs_${oracle_sid}": - path => "${oracle_oralogs}/${oracle_sid}", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_oralogs"], - before => [ - File["oracle_oralogs_redo"], - File["oracle_oralogs_ctl"], - File["oracle_oralogs_arch"] - ], - mode => 755 - } - - oracle_dir{ - "oracle_oralogs_redo": - path => "${oracle_oralogs}/${oracle_sid}/redo", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_oralogs_${oracle_sid}"], - mode => 755 - } - - oracle_dir{ - "oracle_oralogs_ctl": - path => "${oracle_oralogs}/${oracle_sid}/ctl", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_oralogs_${oracle_sid}"], - mode => 755 - } - - oracle_dir{ - "oracle_oralogs_arch": - path => "${oracle_oralogs}/${oracle_sid}/arch", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_oralogs_${oracle_sid}"], - mode => 755 - } - - oracle_dir { - "oracle_oradata": - path => "/data/oracle/oradata", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_data"], - before => File["oracle_oradata_${oracle_sid}"], - mode => 755 - } - - oracle_dir { - "oracle_oradata_${oracle_sid}": - path => "/data/oracle/oradata/${oracle_sid}", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_oradata"], - mode => 755 - - } - - $oracle_logs = "/logs/oracle" - oracle_dir { - "oracle_logs": - path => "${oracle_logs}", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["/logs"], - mode => 755, - before => [ - File["oracle_dumps"], - File["oracle_user_dumps"], - File["oracle_background_dumps"], - File["oracle_audit_dumps"], - File["oracle_core_dumps"] - ] - } - - $oracle_dumps = "${oracle_logs}/oradumps" - oracle_dir { - "oracle_dumps": - path => "${oracle_dumps}", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_logs"], - before => [ - File["oracle_user_dumps"], - File["oracle_background_dumps"], - File["oracle_audit_dumps"], - File["oracle_core_dumps"], - File["oracle_pfile_dir"], - File["oracle_dumps_${oracle_sid}"] - ] , - mode => 755 - } - - oracle_dir { - "oracle_dumps_${oracle_sid}": - path => "/logs/oracle/oradumps/${oracle_sid}", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_dumps"], - before => [ - File["oracle_user_dumps"], - File["oracle_background_dumps"], - File["oracle_audit_dumps"], - File["oracle_core_dumps"], - File["oracle_pfile_dir"] - ], - mode => 755 - } - - oracle_dir { - "oracle_user_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/udump", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_dumps_${oracle_sid}"], - mode => 755 - } - - oracle_dir { - "oracle_background_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/bdump", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_dumps_${oracle_sid}"], - mode => 755 - } - - oracle_dir { - "oracle_audit_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/adump", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_dumps_${oracle_sid}"], - mode => 755 - } - - oracle_dir { - "oracle_core_dumps": - path => "/logs/oracle/oradumps/${oracle_sid}/cdump", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_dumps_${oracle_sid}"], - mode => 755 - } - - oracle_dir { - "oracle_pfile_dir": - path => "/logs/oracle/oradumps/${oracle_sid}/pfile", - ensure => directory, - owner => "oracle", - group => "dba", - require => File["oracle_dumps_${oracle_sid}"], - mode => 755 - } - - -} # end of class oracle::database_server::directories - - -class oracle::database_server::system_packages { - - case $operatingsystem { - "solaris": { - $sun_provider = "sun" - case $oracle_major_version { - "10g": { - case $architecture { - "sparc64": { - $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] - } - "sparc32": { - $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] - } - default: { - fail("oracle::database_server - the architecture $architecture is not - yet supported by class system_packages.") - } - } - } - "9i": { - case $architecture { - "sparc64": { - $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] - } - "sparc32": { - $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] - } - - default: { - fail("oracle::database_server - the architecture $architecture is not - yet supported by class system_packages.") - } - } - } - - default: { - fail("oracle::database_server - the oracle version $oracle_major_version is not - yet support by class system_packages.") - } - } - } - default: { - fail("oracle::database_server - the operating system $operatingsystem is not - yet supported by class system_packages.") - } - - } - - notify {"oracle::database_server - the operating system is ${operatingsystem}": } - notify {"oracle::database_server - the architecture is ${architecture}": } - notify {"oracle::database_server - the architecture is ${oracle_major_version}": } - notify {"oracle::database_server - the list of packages required is ${system_packages}": } - - package { $ystem_packages: ensure => installed, provider => $sun_provider } - -} # end of class oracle::database_server::system_packages diff --git a/modules/oracle/manifests/directories.pp b/modules/oracle/manifests/directories.pp new file mode 100644 index 0000000..aab6144 --- /dev/null +++ b/modules/oracle/manifests/directories.pp @@ -0,0 +1,358 @@ +# directories.pp - oracle database server software 9i/10g +# +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +class oracle::directories { + + define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { + file { + $name: + path => $path, + ensure => $ensure, + force => true, + owner => $owner, + group => $group, + recurse => false, + mode => $mode + } + } + + + # required directories + oracle_dir { + "var_opt": + path => "/var/opt", + ensure => directory, + owner => "root", + group => "root", + before => File["var_opt_oracle"], + mode => 755 + } + + oracle_dir { + "/logs": + path => "/logs", + ensure => directory, + owner => "root", + group => "root", + before => File["oracle_logs"], + mode => 755 + } + + oracle_dir { + "/data": + path => "/data", + ensure => directory, + owner => "root", + group => "root", + before => File["oracle_data"], + mode => 755 + } + + oracle_dir { + "var_opt_oracle": + path => "/var/opt/oracle", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => File["var_opt"], + mode => 755 + } + + oracle_dir { + "/opt/applications": + path => "/opt/applications", + ensure => directory, + owner => "root", + group => "root", + before => File["oracle_base"], + mode => 755 + } + + $oracle_base_path = "/opt/applications/oracle" + $orainventory_path = "$oracle_base_path/oraInventory" + file { + "/var/opt/oracle/oraInst.loc": + content => template("oracle/oraInst-template.erb"), + ensure => present, + force => true, + owner => "oracle", + group => "oinstall", + mode => 644 + } + + oracle_dir { + "oracle_base": + path => $oracle_base_path, + ensure => directory, + owner => "oracle", + group => "oinstall", + before => [ + File["oracle_home"], + File["oracle_major_version"], + File["oracle_version"] + ], + require => File["/opt/applications"], + mode => 755 + } + +# $oracle_inventory_path = "${oracle_base_path}/oraInventory" +# oracle_dir { +# "oracle_inventory": +# path => $oracle_inventory_path, +# ensure => directory, +# owner => "oracle", +# group => "oinstall", +# mode => 775 +# } + + oracle_dir { + "oracle_major_version": + path => "${oracle_base_path}/${oracle_major_version}", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => File["oracle_base"], + before => [ + File["oracle_home"], + File["oracle_version"] + ], + mode => 755 + } + + oracle_dir { + "oracle_version": + path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => [ + File["oracle_base"], + File["oracle_major_version"] + ], + before => File["oracle_home"] , + mode => 755 + } + + $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" + oracle_dir { + "oracle_home": + path => "${oracle_home_path}", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => [ + File["oracle_base"], + File["oracle_major_version"], + File["oracle_version"] + ], + mode => 755 + } + + oracle_dir { + "oracle_data": + path => "/data/oracle", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["/data"], + mode => 755 + } + + $oracle_oralogs = "/data/oracle/oralogs" + oracle_dir { + "oracle_oralogs": + path => "${oracle_oralogs}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_data"], + mode => 755 + } + + oracle_dir { + "oracle_oralogs_${oracle_sid}": + path => "${oracle_oralogs}/${oracle_sid}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs"], + before => [ + File["oracle_oralogs_redo"], + File["oracle_oralogs_ctl"], + File["oracle_oralogs_arch"] + ], + mode => 755 + } + + oracle_dir{ + "oracle_oralogs_redo": + path => "${oracle_oralogs}/${oracle_sid}/redo", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs_${oracle_sid}"], + mode => 755 + } + + oracle_dir{ + "oracle_oralogs_ctl": + path => "${oracle_oralogs}/${oracle_sid}/ctl", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs_${oracle_sid}"], + mode => 755 + } + + oracle_dir{ + "oracle_oralogs_arch": + path => "${oracle_oralogs}/${oracle_sid}/arch", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_oradata": + path => "/data/oracle/oradata", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_data"], + before => File["oracle_oradata_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_oradata_${oracle_sid}": + path => "/data/oracle/oradata/${oracle_sid}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oradata"], + mode => 755 + + } + + $oracle_logs = "/logs/oracle" + oracle_dir { + "oracle_logs": + path => "${oracle_logs}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["/logs"], + mode => 755, + before => [ + File["oracle_dumps"], + File["oracle_user_dumps"], + File["oracle_background_dumps"], + File["oracle_audit_dumps"], + File["oracle_core_dumps"] + ] + } + + $oracle_dumps = "${oracle_logs}/oradumps" + oracle_dir { + "oracle_dumps": + path => "${oracle_dumps}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_logs"], + before => [ + File["oracle_user_dumps"], + File["oracle_background_dumps"], + File["oracle_audit_dumps"], + File["oracle_core_dumps"], + File["oracle_pfile_dir"], + File["oracle_dumps_${oracle_sid}"] + ] , + mode => 755 + } + + oracle_dir { + "oracle_dumps_${oracle_sid}": + path => "/logs/oracle/oradumps/${oracle_sid}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps"], + before => [ + File["oracle_user_dumps"], + File["oracle_background_dumps"], + File["oracle_audit_dumps"], + File["oracle_core_dumps"], + File["oracle_pfile_dir"] + ], + mode => 755 + } + + oracle_dir { + "oracle_user_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/udump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_background_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/bdump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_audit_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/adump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_core_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/cdump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_pfile_dir": + path => "/logs/oracle/oradumps/${oracle_sid}/pfile", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + +} # end of class oracle::directories diff --git a/modules/oracle/manifests/server.pp b/modules/oracle/manifests/server.pp new file mode 100644 index 0000000..6747639 --- /dev/null +++ b/modules/oracle/manifests/server.pp @@ -0,0 +1,32 @@ +# server.pp - oracle database server software 9i/10g +# +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +class oracle::server { + + include oracle::administrators + include oracle::system_packages + +} # end of class oracle::server + +class oracle::server::database inherits oracle::server { + include oracle::directories + include oracle::system_profile +} + +class oracle::server::database::enterprise inherits oracle::server::database { + include oracle::software +} diff --git a/modules/oracle/manifests/software.pp b/modules/oracle/manifests/software.pp new file mode 100644 index 0000000..b130c62 --- /dev/null +++ b/modules/oracle/manifests/software.pp @@ -0,0 +1,140 @@ +# software.pp - oracle database server software 9i/10g +# +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +### +### software class is responsible to silent install from a response file +### database server enterprise software only +### +class oracle::software { + + $oracle_base_software = "/opt/applications/repository/oracle/database_server" + + define install_oracle_database_server_software($oracle_version) { + case $operatingsystem { + default: { err ("unknown operation system value ${operatingsystem}") } + solaris: { + case $oracle_version { + default: {err("unknown oracle version value ${oracle_version}") } + "9.2.0.8": { + $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" + $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" + $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" + $current_oracle_home = $oracle::directories::oracle_home_path + $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" + $current_oracle_base = $oracle::directories::oracle_base_path + $orainventory_path = "$current_oracle_base/oraInventory" + $tmp_dir = "/var/tmp" + + # build a script to run silent installer + # of 11.2.0.1 Disk 1 Oracle database + # server software enterprise edition + file{ + "wruninstaller_9.2.0.1.sh": + name => "${tmp_dir}/wruninstaller_9.2.0.1.sh", + content => template("oracle/wruninstaller_9.2.0.1-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + } + + # run silent installer of 9.2.0.1 Disk 1 + # Orable database server software + # enterprise edition + exec { + "runinstaller-oui": + command => "wruninstaller_9.2.0.1.sh > ${tmp_dir}/runinstaller-oui_9.2.0.1.log", + path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + creates => "/var/opt/oracle/9.2.0.1_installed", + group => "oinstall", + user => "oracle", + environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => File ["wruninstaller_9.2.0.1.sh"], + timeout => "-1", + } + + + $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" + $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" + $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" + + # build a script to run silent installer + # of 9.2.0.8 Disk 1 Oracle database + # server software enterprise edition + # patchset + file{ + "wruninstaller_9.2.0.8_patchset.sh": + name => "${tmp_dir}/wruninstaller_9.2.0.8_patchset.sh", + content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + } + + # run silent installer of 9.2.0.8 Disk 1 + # Orable database server software + # enterprise edition patchset + exec { + "runinstaller-patchset-oui": + command => + "wruninstaller_9.2.0.8_patchset.sh > ${tmp_dir}/runinstaller-patchset-oui_9.2.0.8.log", + path => ["/usr/bin", + "/usr/sbin", + ".", + "/opt/csw/bin", + "/usr/sbin", + "/usr/bin", + "/usr/dt/bin", + "/usr/openwin/bin", + "/usr/ccs/bin", + "/usr/sfw/bin", + "/usr/perl5/5.8.4/bin", + "/opt/SUNWspro/bin"], + cwd => "${tmp_dir}", + creates => "/var/opt/oracle/9.2.0.8_patchset_installed", + group => "oinstall", + user => "oracle", + environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File ["wruninstaller_9.2.0.8_patchset.sh"], + Exec ["runinstaller-oui"] + ], + timeout => "-1", + } + + + } + "10.2.0.4": { + + + } + } + } + } + } + + install_oracle_database_server_software { + "oracle database enterprise software": + oracle_version => $oracle_version, + } +} + diff --git a/modules/oracle/manifests/system_packages.pp b/modules/oracle/manifests/system_packages.pp new file mode 100644 index 0000000..5b357a6 --- /dev/null +++ b/modules/oracle/manifests/system_packages.pp @@ -0,0 +1,70 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + + +class oracle::system_packages { + + case $operatingsystem { + "solaris": { + $sun_provider = "sun" + case $oracle_major_version { + "10g": { + case $architecture { + "sparc64": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] + } + "sparc32": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] + } + default: { + fail("INFO - the architecture $architecture is not + yet supported by class system_packages.") + } + } + } + "9i": { + case $architecture { + "sparc64": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] + } + "sparc32": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] + } + + default: { + fail("INFO - the architecture $architecture is not + yet supported by class system_packages.") + } + } + } + + default: { + fail("INFO - the oracle version $oracle_major_version is not + yet support by class system_packages.") + } + } + } + } + + notify {"INFO - the operating system is ${operatingsystem}": } + notify {"INFO - the architecture is ${architecture}": } + notify {"INFO - the architecture is ${oracle_major_version}": } + notify {"INFO - the list of packages required is ${system_packages}": } + + package { $ystem_packages: ensure => installed, provider => $sun_provider } + +}# end of class oracle::system_packages diff --git a/modules/oracle/manifests/system_profile.pp b/modules/oracle/manifests/system_profile.pp new file mode 100644 index 0000000..bb7b27b --- /dev/null +++ b/modules/oracle/manifests/system_profile.pp @@ -0,0 +1,52 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +### +### system_profile class is responsible to set up the correct operating +### system profile that is build from a template and inherit variables. +### The system profile will export the famous ORACLE_HOME, +### ORACLE_SID, ... and else environment variables. +### +class oracle::system_profile { + define oracle_system_profile ($oracle_base_path, $oracle_version, + $oracle_home_path, $oracle_sid, + $oracle_dumps, $oracle_oralogs) { + file { + $name: + content => +template("oracle/bash_profile.oracle-template.erb"), + mode => 0644, owner => oracle, group => dba + } + } + + oracle_system_profile { + "/users/oracle/.bash_profile.oracle": + oracle_base_path => + $oracle::directories::oracle_base_path, + oracle_version => + $oracle::directories::oracle_version, +oracle_home_path => + $oracle::directories::oracle_home_path, + oracle_sid => + $oracle::directories::oracle_sid, +oracle_dumps => + $oracle::directories::oracle_dumps, + oracle_oralogs => + $oracle::directories::oracle_oralogs + } +} # end of class oracle::system_profile + diff --git a/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb index 8f7d85a..9d1920b 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb @@ -1,57 +1,60 @@ #!/usr/bin/bash echo " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"<%= disk2_9201_path %>\" LOCATION_FOR_DISK3=\"<%= disk3_9201_path %>\" s_cfgtyperet=\"Software Only\" " +cd <%= disk1_9201_path %> + ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" LOCATION_FOR_DISK2="<%= disk2_9201_path %>" LOCATION_FOR_DISK3="<%= disk3_9201_path %>" s_cfgtyperet="Software Only" orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" function test_pad() { file=$1 sleep 120 grep 'was successful' $file if [ $? -eq 1 ]; then return 0; fi return 1 } function reverse() { string=$1 len=$(echo -n $string | wc -c) while test $len -gt 0 do rev=$rev$(echo $string | cut -c $len) len=$(( len - 1 )) done echo $rev } ANIM="//--\\||" PAD=" " SLEEP="0.1" ANIM_L="$(reverse $ANIM)" PAD_LN=${#PAD} ANIM_LN=${#ANIM} u=0; re=0; l=0 echo "Parsing log: ${oracle_install_log_path} for successful install message..." while test_pad $oracle_install_log_path; do if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi u=$(( u + 1 )); l=$(( l + 1 )) if [ $l -eq $ANIM_LN ]; then l=0; fi sleep $SLEEP + echo "Parsing log and sleeping $SLEEP..." done touch /var/opt/oracle/9.2.0.1_installed echo "The installation of Oracle9i 9.2.0.1 Database was successful." exit 0 diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb index aca79be..bbe9986 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb @@ -1,57 +1,59 @@ #!/usr/bin/bash echo " Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" " +cd <%= disk1_9208_patchset_path %> + ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" function test_pad() { file=$1 sleep 120 grep 'was successful' $file if [ $? -eq 1 ]; then return 0; fi return 1 } function reverse() { string=$1 len=$(echo -n $string | wc -c) while test $len -gt 0 do rev=$rev$(echo $string | cut -c $len) len=$(( len - 1 )) done echo $rev } ANIM="//--\\||" PAD=" " SLEEP="0.1" ANIM_L="$(reverse $ANIM)" PAD_LN=${#PAD} ANIM_LN=${#ANIM} u=0; re=0; l=0 echo "Parsing log: ${oracle_install_log_path} for successful install message..." while test_pad $oracle_install_log_path; do if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi u=$(( u + 1 )); l=$(( l + 1 )) if [ $l -eq $ANIM_LN ]; then l=0; fi sleep $SLEEP done touch /var/opt/oracle/9.2.0.8_patchset_installed echo "The installation of Oracle9i patchset 9.2.0.8 Database was successful." exit 0
jeremybaumont/Oracle-puppet-module
0361a8b7e611c83c68830f630b8c07a72bf4d3f1
Added exec resource to install 9.2.0.8 patchset
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f9bbced --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.[oa] +*~ +*.swp diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 595f794..cefa4f5 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,509 +1,567 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile # required oracle software include oracle::database_server::software } # end of class oracle::database_server ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::database_server::software { $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version}") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::database_server::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::database_server::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" - + # build a script to run silent installer + # of 11.2.0.1 Disk 1 Oracle database + # server software enterprise edition file{ - "wruninstaller_${oracle_version}.sh": - name => "${disk1_9201_path}/wruninstaller_${oracle_version}.sh", - content => template("oracle/wruninstaller_${oracle_version}-template.erb"), + "wruninstaller_9.2.0.1.sh": + name => "${disk1_9201_path}/wruninstaller_9.2.0.1.sh", + content => template("oracle/wruninstaller_9.2.0.1-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } - + + # run silent installer of 9.2.0.1 Disk 1 + # Orable database server software + # enterprise edition exec { "runinstaller-oui": - command => "wruninstaller_${oracle_version}.sh >/var/tmp/runinstaller-oui.log", + command => "wruninstaller_9.2.0.1.sh >/var/tmp/runinstaller-oui_9.2.0.1.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${disk1_9201_path}", - creates => "/var/opt/oracle/${oracle_version}_installed", + creates => "/var/opt/oracle/9.2.0.1_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], - require => File ["wruninstaller_${oracle_version}.sh"], + require => File ["wruninstaller_9.2.0.1.sh"], timeout => "-1", } + + + $disk1_9208_patchset_path = "${oracle_base_software}/${architecture}/patchset_9.2.0.8/Disk1" + $responsefile_patchset_path = "${disk1_9208_patchset_path}/response/patchset.rsp" + $products_patchset_path = "${disk1_9208_patchset_path}/stage/products.xml" + + # build a script to run silent installer + # of 9.2.0.8 Disk 1 Oracle database + # server software enterprise edition + # patchset + file{ + "wruninstaller_9.2.0.8_patchset.sh": + name => "${disk1_9208_patchset_path}/wruninstaller_9.2.0.8_patchset.sh", + content => template("oracle/wruninstaller_9.2.0.8_patchset-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + } + + # run silent installer of 9.2.0.8 Disk 1 + # Orable database server software + # enterprise edition patchset + exec { + "runinstaller-patchset-oui": + command => + "wruninstaller_9.2.0.8_patchset.sh >/var/tmp/runinstaller-patchset-oui_9.2.0.8.log", + path => ["/usr/bin", + "/usr/sbin", + ".", + "/opt/csw/bin", + "/usr/sbin", + "/usr/bin", + "/usr/dt/bin", + "/usr/openwin/bin", + "/usr/ccs/bin", + "/usr/sfw/bin", + "/usr/perl5/5.8.4/bin", + "/opt/SUNWspro/bin"], + cwd => "${disk1_9208_patchset_path}", + creates => "/var/opt/oracle/9.2.0.8_patchset_installed", + group => "oinstall", + user => "oracle", + environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + require => [ + File ["wruninstaller_9.2.0.8_patchset.sh"], + Exec ["runinstaller-oui"] + ], + timeout => "-1", + } + + } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } ### ### system_profile class is responsible to set up the correct operating ### system profile that is build from a template and inherit variables. ### The system profile will export the famous ORACLE_HOME, ### ORACLE_SID, ... and else environment variables. ### class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile ### ### ### ### class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, - recurse => 5, + recurse => false, mode => $mode } } # required directories oracle_dir { "var_opt": path => "/var/opt", ensure => directory, owner => "root", group => "root", before => File["var_opt_oracle"], mode => 755 } oracle_dir { "var_opt_oracle": path => "/var/opt/oracle", ensure => directory, owner => "oracle", group => "oinstall", require => File["var_opt"], mode => 755 } $oracle_base_path = "/opt/applications/oracle" $orainventory_path = "$oracle_base_path/oraInventory" file { "/var/opt/oracle/oraInst.loc": content => template("oracle/oraInst-template.erb"), ensure => present, force => true, owner => "oracle", group => "oinstall", mode => 644 } oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } # $oracle_inventory_path = "${oracle_base_path}/oraInventory" # oracle_dir { # "oracle_inventory": # path => $oracle_inventory_path, # ensure => directory, # owner => "oracle", # group => "oinstall", # mode => 775 # } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/manifests/virt_groups.pp b/modules/oracle/manifests/virt_groups.pp index 7d95de6..ff6bdb3 100644 --- a/modules/oracle/manifests/virt_groups.pp +++ b/modules/oracle/manifests/virt_groups.pp @@ -1,28 +1,28 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_groups { @group { dba: - gid => 500, + gid => 4000, ensure => present, } @group { oinstall: gid => 501, ensure => present, } } diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index be7bba3..a433363 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,55 +1,56 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, + uid => 4000, gid => "dba", groups => [ "oinstall" , "other" ], comment => "Oracle Application User", home => "/users/oracle", require => [ Group["dba"], Group["oinstall"] ] , shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": source => "$fileserver/users/oracle/.bashrc", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": source => "$fileserver/users/oracle/.bash_profile", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": source => "$fileserver/users/oracle/.ssh/authorized_keys", ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": # source => "$fileserver/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } } diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb similarity index 98% rename from modules/oracle/templates/wruninstaller_9.2.0.8-template.erb rename to modules/oracle/templates/wruninstaller_9.2.0.1-template.erb index ab49e2e..8f7d85a 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.1-template.erb @@ -1,56 +1,57 @@ #!/usr/bin/bash echo " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"<%= disk2_9201_path %>\" LOCATION_FOR_DISK3=\"<%= disk3_9201_path %>\" s_cfgtyperet=\"Software Only\" " ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" LOCATION_FOR_DISK2="<%= disk2_9201_path %>" LOCATION_FOR_DISK3="<%= disk3_9201_path %>" s_cfgtyperet="Software Only" orainventory_path=<%= orainventory_path %> oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" function test_pad() { file=$1 sleep 120 grep 'was successful' $file if [ $? -eq 1 ]; then return 0; fi return 1 } function reverse() { string=$1 len=$(echo -n $string | wc -c) while test $len -gt 0 do rev=$rev$(echo $string | cut -c $len) len=$(( len - 1 )) done echo $rev } ANIM="//--\\||" PAD=" " SLEEP="0.1" ANIM_L="$(reverse $ANIM)" PAD_LN=${#PAD} ANIM_LN=${#ANIM} u=0; re=0; l=0 echo "Parsing log: ${oracle_install_log_path} for successful install message..." while test_pad $oracle_install_log_path; do if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi u=$(( u + 1 )); l=$(( l + 1 )) if [ $l -eq $ANIM_LN ]; then l=0; fi sleep $SLEEP done - -echo "The installation of Oracle9i Database was successful." +touch /var/opt/oracle/9.2.0.1_installed +echo "The installation of Oracle9i 9.2.0.1 Database was successful." +exit 0 diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb new file mode 100644 index 0000000..aca79be --- /dev/null +++ b/modules/oracle/templates/wruninstaller_9.2.0.8_patchset-template.erb @@ -0,0 +1,57 @@ +#!/usr/bin/bash + + +echo " Running the oracle silent install ./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" " + +./runInstaller -silent -ignoreSysPrereqs -responseFile <%= responsefile_patchset_path %> FROM_LOCATION="<%= products_patchset_path %>" ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" + +orainventory_path=<%= orainventory_path %> +oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` +oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" + +function test_pad() +{ + file=$1 + + sleep 120 + grep 'was successful' $file + if [ $? -eq 1 ]; then return 0; fi + + return 1 +} + + +function reverse() +{ + string=$1 + len=$(echo -n $string | wc -c) + while test $len -gt 0 + do + rev=$rev$(echo $string | cut -c $len) + len=$(( len - 1 )) + done + echo $rev +} + +ANIM="//--\\||" +PAD=" " +SLEEP="0.1" + +ANIM_L="$(reverse $ANIM)" +PAD_LN=${#PAD} +ANIM_LN=${#ANIM} +u=0; re=0; l=0 + +echo "Parsing log: ${oracle_install_log_path} for successful install message..." +while test_pad $oracle_install_log_path; do + if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi + if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi + echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" + if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi + u=$(( u + 1 )); l=$(( l + 1 )) + if [ $l -eq $ANIM_LN ]; then l=0; fi + sleep $SLEEP +done +touch /var/opt/oracle/9.2.0.8_patchset_installed +echo "The installation of Oracle9i patchset 9.2.0.8 Database was successful." +exit 0
jeremybaumont/Oracle-puppet-module
ab8ada61bcebd1bba567c8336425282f63900630
fix wrapped install oracle soft script
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 51e3597..595f794 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,514 +1,509 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile # required oracle software include oracle::database_server::software } # end of class oracle::database_server ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::database_server::software { $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version}") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::database_server::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" $current_oracle_base = $oracle::database_server::directories::oracle_base_path $orainventory_path = "$current_oracle_base/oraInventory" - file { - "oraInst.loc": - name => "/var/opt/oracle/oraInst.loc", - content => template("oracle/oraInst-template.erb"), - mode => 0644, - owner => "oracle", - group => "oinstall", - } file{ "wruninstaller_${oracle_version}.sh": name => "${disk1_9201_path}/wruninstaller_${oracle_version}.sh", content => template("oracle/wruninstaller_${oracle_version}-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } exec { "runinstaller-oui": - command => "wruninstaller_${oracle_version}.sh ", + command => "wruninstaller_${oracle_version}.sh >/var/tmp/runinstaller-oui.log", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${disk1_9201_path}", creates => "/var/opt/oracle/${oracle_version}_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => File ["wruninstaller_${oracle_version}.sh"], + timeout => "-1", } } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } ### ### system_profile class is responsible to set up the correct operating ### system profile that is build from a template and inherit variables. ### The system profile will export the famous ORACLE_HOME, ### ORACLE_SID, ... and else environment variables. ### class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile ### ### ### ### class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories -# oracle_dir { -# "var_opt": -# path => "/var/opt", -# ensure => directory, -# owner => "root", -# group => "root", -# before => File["var_opt_oracle"], -# mode => 755 -# } -# -# oracle_dir { -# "var_opt_oracle": -# path => "/var/opt/oracle", -# ensure => directory, -# owner => "oracle", -# group => "oinstall", -# require => File["var_opt"], -# mode => 755 -# } -# -# file { -# "/var/opt/oracle/oraInst.loc": -# ensure => present, -# force => true, -# owner => "oracle", -# group => "oinstall", -# mode => 644 -# } + oracle_dir { + "var_opt": + path => "/var/opt", + ensure => directory, + owner => "root", + group => "root", + before => File["var_opt_oracle"], + mode => 755 + } + oracle_dir { + "var_opt_oracle": + path => "/var/opt/oracle", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => File["var_opt"], + mode => 755 + } + $oracle_base_path = "/opt/applications/oracle" + $orainventory_path = "$oracle_base_path/oraInventory" + file { + "/var/opt/oracle/oraInst.loc": + content => template("oracle/oraInst-template.erb"), + ensure => present, + force => true, + owner => "oracle", + group => "oinstall", + mode => 644 + } + oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } # $oracle_inventory_path = "${oracle_base_path}/oraInventory" # oracle_dir { # "oracle_inventory": # path => $oracle_inventory_path, # ensure => directory, # owner => "oracle", # group => "oinstall", # mode => 775 # } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb index 35a9bbd..ab49e2e 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb @@ -1,6 +1,56 @@ -#!/usr/bin/bash +#!/usr/bin/bash echo " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"<%= disk2_9201_path %>\" LOCATION_FOR_DISK3=\"<%= disk3_9201_path %>\" s_cfgtyperet=\"Software Only\" " ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" LOCATION_FOR_DISK2="<%= disk2_9201_path %>" LOCATION_FOR_DISK3="<%= disk3_9201_path %>" s_cfgtyperet="Software Only" + +orainventory_path=<%= orainventory_path %> +oracle_install_log=`ls -lrt ${orainventory_path}/logs |grep oraInstall | grep out | tail -1 | awk '{print $9}'` +oracle_install_log_path="${orainventory_path}/logs/${oracle_install_log}" + +function test_pad() +{ + file=$1 + + sleep 120 + grep 'was successful' $file + if [ $? -eq 1 ]; then return 0; fi + + return 1 +} + + +function reverse() +{ + string=$1 + len=$(echo -n $string | wc -c) + while test $len -gt 0 + do + rev=$rev$(echo $string | cut -c $len) + len=$(( len - 1 )) + done + echo $rev +} + +ANIM="//--\\||" +PAD=" " +SLEEP="0.1" + +ANIM_L="$(reverse $ANIM)" +PAD_LN=${#PAD} +ANIM_LN=${#ANIM} +u=0; re=0; l=0 + +echo "Parsing log: ${oracle_install_log_path} for successful install message..." +while test_pad $oracle_install_log_path; do + if [ $re -eq 1 ]; then L=$ANIM_L; else L=$ANIM; fi + if [ $re -eq 1 ]; then p=$(( $PAD_LN - $u )); else p=$u; fi + echo -ne "${PAD:0:$p} ${L:$l:1} ${PAD:$p:$PAD_LN} \r" + if [ $u -eq $PAD_LN ]; then u=0; if [ $re -eq 1 ]; then re=0; else re=1; fi; fi + u=$(( u + 1 )); l=$(( l + 1 )) + if [ $l -eq $ANIM_LN ]; then l=0; fi + sleep $SLEEP +done + +echo "The installation of Oracle9i Database was successful."
jeremybaumont/Oracle-puppet-module
2d7d5ffaea1910fbff4b00f72ecf824bbc77ca0f
fix X display requirement for X connection
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 809955d..51e3597 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,503 +1,514 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile # required oracle software include oracle::database_server::software } # end of class oracle::database_server ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::database_server::software { $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version}") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::database_server::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" + $current_oracle_base = $oracle::database_server::directories::oracle_base_path + $orainventory_path = "$current_oracle_base/oraInventory" + + file { + "oraInst.loc": + name => "/var/opt/oracle/oraInst.loc", + content => template("oracle/oraInst-template.erb"), + mode => 0644, + owner => "oracle", + group => "oinstall", + } file{ "wruninstaller_${oracle_version}.sh": name => "${disk1_9201_path}/wruninstaller_${oracle_version}.sh", - content => template("wruninstaller_${oracle_version}-template.erb"), + content => template("oracle/wruninstaller_${oracle_version}-template.erb"), mode => 755, owner => "oracle", group => "oinstall", } exec { "runinstaller-oui": command => "wruninstaller_${oracle_version}.sh ", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${disk1_9201_path}", creates => "/var/opt/oracle/${oracle_version}_installed", group => "oinstall", user => "oracle", - environment => ["DISPLAY=:0.0", "[email protected]"], + environment => ["DISPLAY=p-reduck.euronet.nl:0.0", "[email protected]"], logoutput => true, returns => [0,1], require => File ["wruninstaller_${oracle_version}.sh"], } } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": oracle_version => $oracle_version, } } ### ### system_profile class is responsible to set up the correct operating ### system profile that is build from a template and inherit variables. ### The system profile will export the famous ORACLE_HOME, ### ORACLE_SID, ... and else environment variables. ### class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile ### ### ### ### class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories # oracle_dir { # "var_opt": # path => "/var/opt", # ensure => directory, # owner => "root", # group => "root", # before => File["var_opt_oracle"], # mode => 755 # } # # oracle_dir { # "var_opt_oracle": # path => "/var/opt/oracle", # ensure => directory, # owner => "oracle", # group => "oinstall", # require => File["var_opt"], # mode => 755 # } # # file { # "/var/opt/oracle/oraInst.loc": # ensure => present, # force => true, # owner => "oracle", # group => "oinstall", # mode => 644 # } $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } # $oracle_inventory_path = "${oracle_base_path}/oraInventory" # oracle_dir { # "oracle_inventory": # path => $oracle_inventory_path, # ensure => directory, # owner => "oracle", # group => "oinstall", # mode => 775 # } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index 17050fa..a24996d 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,87 +1,89 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } # Display main environment variables inforacle() { log "INFO" "ORACLE_SID=${ORACLE_SID}" log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" log "INFO" "ORACLE_HOME=${ORACLE_HOME}" } # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> # optional oracle unix environmen variables to simplify code review ORACLE_DUMPS=<%= oracle_dumps %> ORACLE_ORALOGS=<%= oracle_oralogs %> export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID # update lib path and command path export PATH=$ORACLE_HOME/bin:$PATH export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH # oracle alias to speed up productivity alias alert='$HOME/dba_alertlog ${ORACLE_DUMPS}/$ORACLE_SID/bdump/alert_$ORACLE_SID.log | tail -200 | less' alias arch='cd ${ORACLE_ORALOGS}/$ORACLE_SID/arch && ls -lrt' alias bdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/bdump && ls -lrt' alias udump='cd ${ORACLE_DUMPS}/$ORACLE_SID/udump && ls -lrt' alias cdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/cdump && ls -lrt' alias adump='cd ${ORACLE_DUMPS}/$ORACLE_SID/adump && ls -lrt' alias pfile='cd ${ORACLE_DUMPS}/$ORACLE_SID/pfile && ls -lrt' alias rm='rm -i' alias sid='env|grep ORACLE_SID' alias i='inforacle' # display oracle main environment at login inforacle # set up X display and term for screen -DISPLAY=:0.0 +# kind of magic here but the silent installer need +# to make an x connection in order to load oui java classes +DISPLAY=p-reduck.euronet.nl:0.0 TERM=vt220 export DISPLAY TERM # keyboard commands stty erase set -o vi diff --git a/modules/oracle/templates/oraInst-template.erb b/modules/oracle/templates/oraInst-template.erb new file mode 100644 index 0000000..1ac120f --- /dev/null +++ b/modules/oracle/templates/oraInst-template.erb @@ -0,0 +1,3 @@ +inventory_loc=<%= orainventory_path %> +inst_group=oinstall + diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb index d596064..35a9bbd 100644 --- a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb +++ b/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb @@ -1,12 +1,6 @@ #!/usr/bin/bash -EXPORT DISPLAY=:0.0 -runInstaller -silent \ - -responseFile <%= responsefile_path %> \ - ORACLE_HOME="<%= current_oracle_home %>" \ - ORACLE_HOME_NAME="<%= oracle_patch_version %>" \ - UNIX_GROUP_NAME="oinstall" \ - LOCATION_FOR_DISK2="<%= disk2_9201_path %>" \ - LOCATION_FOR_DISK3="<%= disk3_9201_path %>" \ - s_cfgtyperet="Software Only" +echo " Running the oracle silent install ./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME=\"<%= current_oracle_home %>\" ORACLE_HOME_NAME=\"<%= oracle_patch_version %>\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"<%= disk2_9201_path %>\" LOCATION_FOR_DISK3=\"<%= disk3_9201_path %>\" s_cfgtyperet=\"Software Only\" " + +./runInstaller -silent -responseFile <%= responsefile_path %> ORACLE_HOME="<%= current_oracle_home %>" ORACLE_HOME_NAME="<%= oracle_patch_version %>" UNIX_GROUP_NAME="oinstall" LOCATION_FOR_DISK2="<%= disk2_9201_path %>" LOCATION_FOR_DISK3="<%= disk3_9201_path %>" s_cfgtyperet="Software Only"
jeremybaumont/Oracle-puppet-module
6944c0cffe74d71d6d6610959eaa55013050a929
add wrapper script that call the silent installer
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index b625533..809955d 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,494 +1,503 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile # required oracle software include oracle::database_server::software } # end of class oracle::database_server ### ### software class is responsible to silent install from a response file ### database server enterprise software only ### class oracle::database_server::software { $oracle_base_software = "/opt/applications/repository/oracle/database_server" define install_oracle_database_server_software($oracle_version) { case $operatingsystem { default: { err ("unknown operation system value ${operatingsystem}") } solaris: { case $oracle_version { default: {err("unknown oracle version value ${oracle_version}") } "9.2.0.8": { $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" $current_oracle_home = $oracle::database_server::directories::oracle_home_path $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" + file{ + "wruninstaller_${oracle_version}.sh": + name => "${disk1_9201_path}/wruninstaller_${oracle_version}.sh", + content => template("wruninstaller_${oracle_version}-template.erb"), + mode => 755, + owner => "oracle", + group => "oinstall", + } + exec { "runinstaller-oui": - command => " nohup runInstaller -silent -responseFile ${responsefile_path} ORACLE_HOME=\"${current_oracle_home}\" ORACLE_HOME_NAME=\"earth\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"${disk2_9201_path}\" LOCATION_FOR_DISK3=\"${disk3_9201_path}\" s_cfgtyperet=\"Software Only\" 2>&1", -# command => "echo \"this should be logged `date` \" ", + command => "wruninstaller_${oracle_version}.sh ", path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], cwd => "${disk1_9201_path}", creates => "/var/opt/oracle/${oracle_version}_installed", group => "oinstall", user => "oracle", environment => ["DISPLAY=:0.0", "[email protected]"], logoutput => true, returns => [0,1], + require => File ["wruninstaller_${oracle_version}.sh"], } } "10.2.0.4": { } } } } } install_oracle_database_server_software { "oracle database enterprise software": - oracle_version => "9.2.0.8", + oracle_version => $oracle_version, } } ### ### system_profile class is responsible to set up the correct operating ### system profile that is build from a template and inherit variables. ### The system profile will export the famous ORACLE_HOME, ### ORACLE_SID, ... and else environment variables. ### class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile ### ### ### ### class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories # oracle_dir { # "var_opt": # path => "/var/opt", # ensure => directory, # owner => "root", # group => "root", # before => File["var_opt_oracle"], # mode => 755 # } # # oracle_dir { # "var_opt_oracle": # path => "/var/opt/oracle", # ensure => directory, # owner => "oracle", # group => "oinstall", # require => File["var_opt"], # mode => 755 # } # # file { # "/var/opt/oracle/oraInst.loc": # ensure => present, # force => true, # owner => "oracle", # group => "oinstall", # mode => 644 # } $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } # $oracle_inventory_path = "${oracle_base_path}/oraInventory" # oracle_dir { # "oracle_inventory": # path => $oracle_inventory_path, # ensure => directory, # owner => "oracle", # group => "oinstall", # mode => 775 # } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index 5ef2da1..17050fa 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,83 +1,87 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } # Display main environment variables inforacle() { log "INFO" "ORACLE_SID=${ORACLE_SID}" log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" log "INFO" "ORACLE_HOME=${ORACLE_HOME}" } # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> # optional oracle unix environmen variables to simplify code review ORACLE_DUMPS=<%= oracle_dumps %> ORACLE_ORALOGS=<%= oracle_oralogs %> export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID +# update lib path and command path +export PATH=$ORACLE_HOME/bin:$PATH +export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH + # oracle alias to speed up productivity alias alert='$HOME/dba_alertlog ${ORACLE_DUMPS}/$ORACLE_SID/bdump/alert_$ORACLE_SID.log | tail -200 | less' alias arch='cd ${ORACLE_ORALOGS}/$ORACLE_SID/arch && ls -lrt' alias bdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/bdump && ls -lrt' alias udump='cd ${ORACLE_DUMPS}/$ORACLE_SID/udump && ls -lrt' alias cdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/cdump && ls -lrt' alias adump='cd ${ORACLE_DUMPS}/$ORACLE_SID/adump && ls -lrt' alias pfile='cd ${ORACLE_DUMPS}/$ORACLE_SID/pfile && ls -lrt' alias rm='rm -i' alias sid='env|grep ORACLE_SID' alias i='inforacle' # display oracle main environment at login inforacle # set up X display and term for screen DISPLAY=:0.0 TERM=vt220 export DISPLAY TERM # keyboard commands stty erase set -o vi diff --git a/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb b/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb new file mode 100644 index 0000000..d596064 --- /dev/null +++ b/modules/oracle/templates/wruninstaller_9.2.0.8-template.erb @@ -0,0 +1,12 @@ +#!/usr/bin/bash + +EXPORT DISPLAY=:0.0 + +runInstaller -silent \ + -responseFile <%= responsefile_path %> \ + ORACLE_HOME="<%= current_oracle_home %>" \ + ORACLE_HOME_NAME="<%= oracle_patch_version %>" \ + UNIX_GROUP_NAME="oinstall" \ + LOCATION_FOR_DISK2="<%= disk2_9201_path %>" \ + LOCATION_FOR_DISK3="<%= disk3_9201_path %>" \ + s_cfgtyperet="Software Only"
jeremybaumont/Oracle-puppet-module
c93ea56fe13f3fd7c590c748168673655a470ef9
add exec resource to install oracle server soft
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 4c0f0db..b625533 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,432 +1,494 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile + # required oracle software + include oracle::database_server::software + } # end of class oracle::database_server +### +### software class is responsible to silent install from a response file +### database server enterprise software only +### +class oracle::database_server::software { + + $oracle_base_software = "/opt/applications/repository/oracle/database_server" + + define install_oracle_database_server_software($oracle_version) { + case $operatingsystem { + default: { err ("unknown operation system value ${operatingsystem}") } + solaris: { + case $oracle_version { + default: {err("unknown oracle version value ${oracle_version}") } + "9.2.0.8": { + $disk1_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk1" + $disk2_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk2" + $disk3_9201_path = "${oracle_base_software}/${architecture}/9.2.0.1/disk3" + $current_oracle_home = $oracle::database_server::directories::oracle_home_path + $responsefile_path = "${disk1_9201_path}/response/enterprise.rsp" + + exec { + "runinstaller-oui": + command => " nohup runInstaller -silent -responseFile ${responsefile_path} ORACLE_HOME=\"${current_oracle_home}\" ORACLE_HOME_NAME=\"earth\" UNIX_GROUP_NAME=\"oinstall\" LOCATION_FOR_DISK2=\"${disk2_9201_path}\" LOCATION_FOR_DISK3=\"${disk3_9201_path}\" s_cfgtyperet=\"Software Only\" 2>&1", +# command => "echo \"this should be logged `date` \" ", + path => ["/usr/bin", "/usr/sbin", ".", "/opt/csw/bin", "/usr/sbin", "/usr/bin", "/usr/dt/bin", "/usr/openwin/bin", "/usr/ccs/bin", "/usr/sfw/bin", "/usr/perl5/5.8.4/bin", "/opt/SUNWspro/bin"], + cwd => "${disk1_9201_path}", + creates => "/var/opt/oracle/${oracle_version}_installed", + group => "oinstall", + user => "oracle", + environment => ["DISPLAY=:0.0", "[email protected]"], + logoutput => true, + returns => [0,1], + } + } + "10.2.0.4": { + + + } + } + } + } + } + + install_oracle_database_server_software { + "oracle database enterprise software": + oracle_version => "9.2.0.8", + } +} + +### +### system_profile class is responsible to set up the correct operating +### system profile that is build from a template and inherit variables. +### The system profile will export the famous ORACLE_HOME, +### ORACLE_SID, ... and else environment variables. +### class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile - +### +### +### +### class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories # oracle_dir { # "var_opt": # path => "/var/opt", # ensure => directory, # owner => "root", # group => "root", # before => File["var_opt_oracle"], # mode => 755 # } # # oracle_dir { # "var_opt_oracle": # path => "/var/opt/oracle", # ensure => directory, # owner => "oracle", # group => "oinstall", # require => File["var_opt"], # mode => 755 # } # # file { # "/var/opt/oracle/oraInst.loc": # ensure => present, # force => true, # owner => "oracle", # group => "oinstall", # mode => 644 # } $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } # $oracle_inventory_path = "${oracle_base_path}/oraInventory" # oracle_dir { # "oracle_inventory": # path => $oracle_inventory_path, # ensure => directory, # owner => "oracle", # group => "oinstall", # mode => 775 # } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages
jeremybaumont/Oracle-puppet-module
036f79cd134139954a79afc4301f91008608b548
fix correct group oinstall to oracle directories
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 2a727ee..4c0f0db 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,432 +1,432 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile } # end of class oracle::database_server class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories # oracle_dir { # "var_opt": # path => "/var/opt", # ensure => directory, # owner => "root", # group => "root", # before => File["var_opt_oracle"], # mode => 755 # } # # oracle_dir { # "var_opt_oracle": # path => "/var/opt/oracle", # ensure => directory, -# owner => "root", -# group => "root", +# owner => "oracle", +# group => "oinstall", # require => File["var_opt"], # mode => 755 # } # # file { # "/var/opt/oracle/oraInst.loc": # ensure => present, # force => true, -# owner => "root", -# group => "root", +# owner => "oracle", +# group => "oinstall", # mode => 644 # } $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } # $oracle_inventory_path = "${oracle_base_path}/oraInventory" # oracle_dir { # "oracle_inventory": # path => $oracle_inventory_path, # ensure => directory, # owner => "oracle", # group => "oinstall", # mode => 775 # } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index 8fe950f..be7bba3 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,53 +1,55 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, - uid => 500, - gid => 500, - groups => ["dba", "oinstall" ], + gid => "dba", + groups => [ "oinstall" , "other" ], comment => "Oracle Application User", home => "/users/oracle", - require => [ Group["dba"], Group["oinstall"] ,] + require => [ + Group["dba"], + Group["oinstall"] + ] , shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": source => "$fileserver/users/oracle/.bashrc", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": source => "$fileserver/users/oracle/.bash_profile", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": source => "$fileserver/users/oracle/.ssh/authorized_keys", ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": # source => "$fileserver/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } }
jeremybaumont/Oracle-puppet-module
1c4bed306174ba20817fd353172610d39d567839
add group oinstall to oracle user
diff --git a/manifests/nodes.pp b/manifests/nodes.pp index 9a02194..fcff523 100644 --- a/manifests/nodes.pp +++ b/manifests/nodes.pp @@ -1,28 +1,28 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # node 'jeremy-test.wanadoo.nl' inherits oracle_database_server { - $architecture = "sparc64" + $architecture = "sparc32" $operatingsystem = "solaris" - $oracle_major_version = "10g" - $oracle_version = "10.2.0.4" + $oracle_major_version = "9i" + $oracle_version = "9.2.0.8" $oracle_patch_version = "earth" $oracle_sid = "PLGRND" include oracle::database_server } diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 9f83ce4..2a727ee 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,393 +1,432 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile } # end of class oracle::database_server class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: content => template("oracle/bash_profile.oracle-template.erb"), mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories +# oracle_dir { +# "var_opt": +# path => "/var/opt", +# ensure => directory, +# owner => "root", +# group => "root", +# before => File["var_opt_oracle"], +# mode => 755 +# } +# +# oracle_dir { +# "var_opt_oracle": +# path => "/var/opt/oracle", +# ensure => directory, +# owner => "root", +# group => "root", +# require => File["var_opt"], +# mode => 755 +# } +# +# file { +# "/var/opt/oracle/oraInst.loc": +# ensure => present, +# force => true, +# owner => "root", +# group => "root", +# mode => 644 +# } + $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } +# $oracle_inventory_path = "${oracle_base_path}/oraInventory" +# oracle_dir { +# "oracle_inventory": +# path => $oracle_inventory_path, +# ensure => directory, +# owner => "oracle", +# group => "oinstall", +# mode => 775 +# } + oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index 4413074..8fe950f 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,52 +1,53 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, uid => 500, gid => 500, + groups => ["dba", "oinstall" ], comment => "Oracle Application User", home => "/users/oracle", - require => Group["dba"], + require => [ Group["dba"], Group["oinstall"] ,] shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": source => "$fileserver/users/oracle/.bashrc", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": source => "$fileserver/users/oracle/.bash_profile", ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": source => "$fileserver/users/oracle/.ssh/authorized_keys", ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": # source => "$fileserver/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } }
jeremybaumont/Oracle-puppet-module
3a5b110027fb598c983e4848d145c1e490dfb484
add unix environment variables in oracle profile
diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index c370942..5ef2da1 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,78 +1,83 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } # Display main environment variables inforacle() { log "INFO" "ORACLE_SID=${ORACLE_SID}" log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" log "INFO" "ORACLE_HOME=${ORACLE_HOME}" } # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> # optional oracle unix environmen variables to simplify code review ORACLE_DUMPS=<%= oracle_dumps %> ORACLE_ORALOGS=<%= oracle_oralogs %> export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID # oracle alias to speed up productivity alias alert='$HOME/dba_alertlog ${ORACLE_DUMPS}/$ORACLE_SID/bdump/alert_$ORACLE_SID.log | tail -200 | less' alias arch='cd ${ORACLE_ORALOGS}/$ORACLE_SID/arch && ls -lrt' alias bdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/bdump && ls -lrt' alias udump='cd ${ORACLE_DUMPS}/$ORACLE_SID/udump && ls -lrt' alias cdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/cdump && ls -lrt' alias adump='cd ${ORACLE_DUMPS}/$ORACLE_SID/adump && ls -lrt' alias pfile='cd ${ORACLE_DUMPS}/$ORACLE_SID/pfile && ls -lrt' alias rm='rm -i' alias sid='env|grep ORACLE_SID' alias i='inforacle' # display oracle main environment at login inforacle +# set up X display and term for screen +DISPLAY=:0.0 +TERM=vt220 +export DISPLAY TERM + # keyboard commands stty erase set -o vi
jeremybaumont/Oracle-puppet-module
7e9cbd1751077773f06b9d84d1e439703bfa7d96
fix issues on the system operating system profiles
diff --git a/manifests/site.pp b/manifests/site.pp index ffeb27a..6a05285 100644 --- a/manifests/site.pp +++ b/manifests/site.pp @@ -1,30 +1,32 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import "templates.pp" import "classes/*" import "groups/*" import "users/*" import "oracle" import "oracle/*.pp" import "nodes.pp" -filebucket { main: server => puppet } +filebucket { main: server => "p-reduck.euronet.nl" } File { backup => main } +# where to fetch files from +$fileserver = "puppet://p-reduck.euronet.nl/files" diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index c456e4d..9f83ce4 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,392 +1,393 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories include oracle::database_server::directories # required system profile include oracle::database_server::system_profile } # end of class oracle::database_server class oracle::database_server::system_profile { define oracle_system_profile ($oracle_base_path, $oracle_version, $oracle_home_path, $oracle_sid, $oracle_dumps, $oracle_oralogs) { file { $name: - content => template("oracle/bash_profile.oracle-template.erb") + content => template("oracle/bash_profile.oracle-template.erb"), + mode => 0644, owner => oracle, group => dba } } oracle_system_profile { "/users/oracle/.bash_profile.oracle": oracle_base_path => $oracle::database_server::directories::oracle_base_path, oracle_version => $oracle::database_server::directories::oracle_version, oracle_home_path => $oracle::database_server::directories::oracle_home_path, oracle_sid => $oracle::database_server::directories::oracle_sid, oracle_dumps => $oracle::database_server::directories::oracle_dumps, oracle_oralogs => $oracle::database_server::directories::oracle_oralogs } } # end of class oracle::database_server::system_profile class oracle::database_server::directories { define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } # required directories $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } } # end of class oracle::database_server::directories class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } # end of class oracle::database_server::system_packages diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index 5465a55..4413074 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,49 +1,52 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, uid => 500, gid => 500, comment => "Oracle Application User", home => "/users/oracle", require => Group["dba"], shell => "/usr/bin/bash", } file { "/users/oracle/": ensure => directory, mode => 0750, owner => oracle, group => dba; "/users/oracle/.bashrc": source => "$fileserver/users/oracle/.bashrc", + ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.bash_profile": - name => "/users/oracle/.bash_profile", + source => "$fileserver/users/oracle/.bash_profile", + ensure => present, replace => true, mode => 0640, owner => oracle, group => dba; "/users/oracle/.ssh": ensure => directory, mode => 0700, owner => oracle, group => dba; "/users/oracle/.ssh/authorized_keys": source => "$fileserver/users/oracle/.ssh/authorized_keys", + ensure => present, replace => true, mode => 0600, owner => oracle, group => dba; # "/users/oracle/.ssh/config": # source => "$fileserver/users/oracle/.ssh/config", # mode => 0600, owner => oracle, group => dba; } } diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb index dbcbac0..c370942 100644 --- a/modules/oracle/templates/bash_profile.oracle-template.erb +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -1,71 +1,78 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Log a message on the output and exit properly log_and_exit() { local type="$1" shift local message="$*" log $type $message exit $EXITCODE } # Log a message on the output log() { local type="$1" shift local message="$*" local dataflags="+%Y.%m.%d,%H:%M:%S" echo "[$type] - `date $dataflags` - $message" } +# Display main environment variables +inforacle() +{ +log "INFO" "ORACLE_SID=${ORACLE_SID}" +log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" +log "INFO" "ORACLE_HOME=${ORACLE_HOME}" +} + # unix prompt oriented for oracle dba PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" # oracle unix environment variables ORACLE_BASE=<%= oracle_base_path %> ORACLE_VERSION=<%= oracle_version %> ORACLE_HOME=<%= oracle_home_path %> ORACLE_SID=<%= oracle_sid %> # optional oracle unix environmen variables to simplify code review ORACLE_DUMPS=<%= oracle_dumps %> ORACLE_ORALOGS=<%= oracle_oralogs %> export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID -log "INFO" "ORACLE_SID=${ORACLE_SID}" -log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" -log "INFO" "ORACLE_HOME=${ORACLE_HOME}" # oracle alias to speed up productivity alias alert='$HOME/dba_alertlog ${ORACLE_DUMPS}/$ORACLE_SID/bdump/alert_$ORACLE_SID.log | tail -200 | less' alias arch='cd ${ORACLE_ORALOGS}/$ORACLE_SID/arch && ls -lrt' alias bdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/bdump && ls -lrt' alias udump='cd ${ORACLE_DUMPS}/$ORACLE_SID/udump && ls -lrt' alias cdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/cdump && ls -lrt' alias adump='cd ${ORACLE_DUMPS}/$ORACLE_SID/adump && ls -lrt' alias pfile='cd ${ORACLE_DUMPS}/$ORACLE_SID/pfile && ls -lrt' alias rm='rm -i' alias sid='env|grep ORACLE_SID' +alias i='inforacle' + +# display oracle main environment at login +inforacle # keyboard commands stty erase set -o vi - -
jeremybaumont/Oracle-puppet-module
64b78147be1e72e71a660a6dea352063d7976feb
add the operating system profile
diff --git a/files/users/oracle/.bash_profile b/files/users/oracle/.bash_profile new file mode 100644 index 0000000..f23d5ad --- /dev/null +++ b/files/users/oracle/.bash_profile @@ -0,0 +1 @@ +source $HOME/.bash_profile.oracle diff --git a/files/users/oracle/.bashrc b/files/users/oracle/.bashrc new file mode 100644 index 0000000..e69de29 diff --git a/files/users/oracle/.ssh/authorized_keys b/files/users/oracle/.ssh/authorized_keys new file mode 100644 index 0000000..a9f2bef --- /dev/null +++ b/files/users/oracle/.ssh/authorized_keys @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1YrAHPlpMxJiRNZurbMfrbLtMmSS8RpnP1hmTCO6ac7MDqK/MEkkrcqfLOvejLViWpRKyEk6ifZDA6kzmyG8PXdL2FT24AtswWPV6vcQjroejXSj8h2q/7GB7dwyDj5MF7q8SfUg3EDx1VoaXf1hs8WIHV1Esd3a4rIZGu3KGQPQg3uyweoeEn/iy6a4b+sBMH3LglmMLd2rFhroZY3J2606IWM3bcJl7wEBmc7Z7rr3jrSn0YpgzOeXIDhnK+nJ5YFp8lNTxEvlkdhlpLH+uAGxS4LVQaTPvwXB3JQrRG3jx/VO0jdPE/gG5G1dl0R7FdlPBJh2frKXukBZJaxpJQ== [email protected] diff --git a/fileserver.conf b/fileserver.conf index dfa6663..52a5c1f 100644 --- a/fileserver.conf +++ b/fileserver.conf @@ -1,33 +1,34 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This file consists of arbitrarily named sections/modules # defining where files are served from and to whom # Define a section 'files' # Adapt the allow/deny settings to your needs. Order # for allow/deny does not matter, allow always takes precedence # over deny [files] path /etc/puppet/files + allow * # allow *.example.com # deny *.evil.example.com # allow 192.168.0.0/24 [plugins] # allow *.example.com # deny *.evil.example.com # allow 192.168.0.0/24 diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index ac4b2ce..c456e4d 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,346 +1,392 @@ # database_server.pp - oracle database server software 9i/10g # # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages + # required directories + include oracle::database_server::directories + + # required system profile + include oracle::database_server::system_profile + +} # end of class oracle::database_server + + +class oracle::database_server::system_profile { + + + define oracle_system_profile ($oracle_base_path, $oracle_version, + $oracle_home_path, $oracle_sid, + $oracle_dumps, $oracle_oralogs) { + file { + $name: + content => template("oracle/bash_profile.oracle-template.erb") + } + } + + oracle_system_profile { + "/users/oracle/.bash_profile.oracle": + oracle_base_path => + $oracle::database_server::directories::oracle_base_path, + oracle_version => + $oracle::database_server::directories::oracle_version, oracle_home_path => + $oracle::database_server::directories::oracle_home_path, + oracle_sid => + $oracle::database_server::directories::oracle_sid, oracle_dumps => + $oracle::database_server::directories::oracle_dumps, + oracle_oralogs => + $oracle::database_server::directories::oracle_oralogs + } +} # end of class oracle::database_server::system_profile + + +class oracle::database_server::directories { + + + define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { + file { + $name: + path => $path, + ensure => $ensure, + force => true, + owner => $owner, + group => $group, + recurse => 5, + mode => $mode + } + } + + # required directories $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], require => File["/opt/applications"], mode => 755 } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } + $oracle_home_path = "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}" oracle_dir { "oracle_home": - path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}", + path => "${oracle_home_path}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_data": path => "/data/oracle", ensure => directory, owner => "oracle", group => "dba", require => File["/data"], mode => 755 } + $oracle_oralogs = "/data/oracle/oralogs" oracle_dir { "oracle_oralogs": - path => "/data/oracle/oralogs", + path => "${oracle_oralogs}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], mode => 755 } oracle_dir { "oracle_oralogs_${oracle_sid}": - path => "/data/oracle/oralogs/${oracle_sid}", + path => "${oracle_oralogs}/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs"], before => [ File["oracle_oralogs_redo"], File["oracle_oralogs_ctl"], File["oracle_oralogs_arch"] ], mode => 755 } oracle_dir{ "oracle_oralogs_redo": - path => "/data/oracle/oralogs/${oracle_sid}/redo", + path => "${oracle_oralogs}/${oracle_sid}/redo", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_ctl": - path => "/data/oracle/oralogs/${oracle_sid}/ctl", + path => "${oracle_oralogs}/${oracle_sid}/ctl", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir{ "oracle_oralogs_arch": - path => "/data/oracle/oralogs/${oracle_sid}/arch", + path => "${oracle_oralogs}/${oracle_sid}/arch", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oralogs_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata": path => "/data/oracle/oradata", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_data"], before => File["oracle_oradata_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_oradata_${oracle_sid}": path => "/data/oracle/oradata/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_oradata"], mode => 755 } + $oracle_logs = "/logs/oracle" oracle_dir { "oracle_logs": - path => "/logs/oracle", + path => "${oracle_logs}", ensure => directory, owner => "oracle", group => "dba", require => File["/logs"], mode => 755, before => [ File["oracle_dumps"], File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"] ] } + $oracle_dumps = "${oracle_logs}/oradumps" oracle_dir { "oracle_dumps": - path => "/logs/oracle/oradumps", + path => "${oracle_dumps}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_logs"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"], File["oracle_dumps_${oracle_sid}"] ] , mode => 755 } oracle_dir { "oracle_dumps_${oracle_sid}": path => "/logs/oracle/oradumps/${oracle_sid}", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps"], before => [ File["oracle_user_dumps"], File["oracle_background_dumps"], File["oracle_audit_dumps"], File["oracle_core_dumps"], File["oracle_pfile_dir"] ], mode => 755 } oracle_dir { "oracle_user_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/udump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_background_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/bdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_audit_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/adump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_core_dumps": path => "/logs/oracle/oradumps/${oracle_sid}/cdump", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } oracle_dir { "oracle_pfile_dir": path => "/logs/oracle/oradumps/${oracle_sid}/pfile", ensure => directory, owner => "oracle", group => "dba", require => File["oracle_dumps_${oracle_sid}"], mode => 755 } -} - -define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { - file { - $name: - path => $path, - ensure => $ensure, - force => true, - owner => $owner, - group => $group, - recurse => 5, - mode => $mode - } -} +} # end of class oracle::database_server::directories + class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } -} +} # end of class oracle::database_server::system_packages diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index 7f1ba1a..5465a55 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,28 +1,49 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::virt_users { @user { oracle: ensure => present, uid => 500, gid => 500, - comment => "Oracle User", - home => "/home/oracle", + comment => "Oracle Application User", + home => "/users/oracle", require => Group["dba"], - shell => "/bin/bash", + shell => "/usr/bin/bash", + } + + file { + "/users/oracle/": + ensure => directory, + mode => 0750, owner => oracle, group => dba; + "/users/oracle/.bashrc": + source => "$fileserver/users/oracle/.bashrc", + mode => 0640, owner => oracle, group => dba; + "/users/oracle/.bash_profile": + name => "/users/oracle/.bash_profile", + mode => 0640, owner => oracle, group => dba; + "/users/oracle/.ssh": + ensure => directory, + mode => 0700, owner => oracle, group => dba; + "/users/oracle/.ssh/authorized_keys": + source => "$fileserver/users/oracle/.ssh/authorized_keys", + mode => 0600, owner => oracle, group => dba; +# "/users/oracle/.ssh/config": +# source => "$fileserver/users/oracle/.ssh/config", +# mode => 0600, owner => oracle, group => dba; } } diff --git a/modules/oracle/templates/bash_profile.oracle-template.erb b/modules/oracle/templates/bash_profile.oracle-template.erb new file mode 100644 index 0000000..dbcbac0 --- /dev/null +++ b/modules/oracle/templates/bash_profile.oracle-template.erb @@ -0,0 +1,71 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +# Log a message on the output and exit properly +log_and_exit() +{ + local type="$1" + shift + local message="$*" + log $type $message + exit $EXITCODE +} + +# Log a message on the output +log() +{ + local type="$1" + shift + local message="$*" + local dataflags="+%Y.%m.%d,%H:%M:%S" + + echo "[$type] - `date $dataflags` - $message" +} + +# unix prompt oriented for oracle dba +PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]`hostname`\[\e[32;1m\])-(\[\e[37;1m\]\@ \d\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]\${ORACLE_SID}\[\e[32;1m\])-> \[\e[0m\]" + +# oracle unix environment variables +ORACLE_BASE=<%= oracle_base_path %> +ORACLE_VERSION=<%= oracle_version %> +ORACLE_HOME=<%= oracle_home_path %> +ORACLE_SID=<%= oracle_sid %> +# optional oracle unix environmen variables to simplify code review +ORACLE_DUMPS=<%= oracle_dumps %> +ORACLE_ORALOGS=<%= oracle_oralogs %> + +export ORACLE_BASE ORACLE_VERSION ORACLE_HOME ORACLE_SID +log "INFO" "ORACLE_SID=${ORACLE_SID}" +log "INFO" "ORACLE_VERSION=${ORACLE_VERSION}" +log "INFO" "ORACLE_HOME=${ORACLE_HOME}" + +# oracle alias to speed up productivity +alias alert='$HOME/dba_alertlog ${ORACLE_DUMPS}/$ORACLE_SID/bdump/alert_$ORACLE_SID.log | tail -200 | less' +alias arch='cd ${ORACLE_ORALOGS}/$ORACLE_SID/arch && ls -lrt' +alias bdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/bdump && ls -lrt' +alias udump='cd ${ORACLE_DUMPS}/$ORACLE_SID/udump && ls -lrt' +alias cdump='cd ${ORACLE_DUMPS}/$ORACLE_SID/cdump && ls -lrt' +alias adump='cd ${ORACLE_DUMPS}/$ORACLE_SID/adump && ls -lrt' +alias pfile='cd ${ORACLE_DUMPS}/$ORACLE_SID/pfile && ls -lrt' +alias rm='rm -i' +alias sid='env|grep ORACLE_SID' + +# keyboard commands +stty erase +set -o vi + +
jeremybaumont/Oracle-puppet-module
3db9286f61d5d4b69433dd9dd9a63b03efd33b5e
add directories resource to database server class
diff --git a/manifests/classes/solaris.pp b/manifests/classes/solaris.pp index 39ee378..7d283cc 100644 --- a/manifests/classes/solaris.pp +++ b/manifests/classes/solaris.pp @@ -1,19 +1,32 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class solaris { - + file { + "/opt/applications": + ensure => directory, + owner => "root", + group => "root"; + "/data": + ensure => directory, + owner => "root", + group => "root"; + "/logs": + ensure => directory, + owner => "root", + group => "root"; + } } diff --git a/manifests/nodes.pp b/manifests/nodes.pp index 04479c0..9a02194 100644 --- a/manifests/nodes.pp +++ b/manifests/nodes.pp @@ -1,27 +1,28 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # -node 'jeremy-test.wanadoo.nl' { +node 'jeremy-test.wanadoo.nl' inherits oracle_database_server { $architecture = "sparc64" - $oracle_major_version = "10g" $operatingsystem = "solaris" + + $oracle_major_version = "10g" $oracle_version = "10.2.0.4" $oracle_patch_version = "earth" + $oracle_sid = "PLGRND" - include oracle::database_server - + include oracle::database_server } diff --git a/manifests/templates.pp b/manifests/templates.pp index 74d27bd..cccd167 100644 --- a/manifests/templates.pp +++ b/manifests/templates.pp @@ -1,30 +1,29 @@ # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # node basenode { case $operatingsystem { solaris: { include solaris } default: { include solaris } } include baseapps } node default inherits basenode{} node oracle_database_server inherits basenode { - include oracle_database_server, oracle_administrators } diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index d603426..ac4b2ce 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,155 +1,346 @@ - +# database_server.pp - oracle database server software 9i/10g +# # Copyright (C) 2009 Jeremy Baumont # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], + require => File["/opt/applications"], mode => 755 } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } oracle_dir { "oracle_home": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } + + oracle_dir { + "oracle_data": + path => "/data/oracle", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["/data"], + mode => 755 + } + + oracle_dir { + "oracle_oralogs": + path => "/data/oracle/oralogs", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_data"], + mode => 755 + } + + oracle_dir { + "oracle_oralogs_${oracle_sid}": + path => "/data/oracle/oralogs/${oracle_sid}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs"], + before => [ + File["oracle_oralogs_redo"], + File["oracle_oralogs_ctl"], + File["oracle_oralogs_arch"] + ], + mode => 755 + } + + oracle_dir{ + "oracle_oralogs_redo": + path => "/data/oracle/oralogs/${oracle_sid}/redo", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs_${oracle_sid}"], + mode => 755 + } + + oracle_dir{ + "oracle_oralogs_ctl": + path => "/data/oracle/oralogs/${oracle_sid}/ctl", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs_${oracle_sid}"], + mode => 755 + } + + oracle_dir{ + "oracle_oralogs_arch": + path => "/data/oracle/oralogs/${oracle_sid}/arch", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oralogs_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_oradata": + path => "/data/oracle/oradata", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_data"], + before => File["oracle_oradata_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_oradata_${oracle_sid}": + path => "/data/oracle/oradata/${oracle_sid}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_oradata"], + mode => 755 + + } + + oracle_dir { + "oracle_logs": + path => "/logs/oracle", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["/logs"], + mode => 755, + before => [ + File["oracle_dumps"], + File["oracle_user_dumps"], + File["oracle_background_dumps"], + File["oracle_audit_dumps"], + File["oracle_core_dumps"] + ] + } + + oracle_dir { + "oracle_dumps": + path => "/logs/oracle/oradumps", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_logs"], + before => [ + File["oracle_user_dumps"], + File["oracle_background_dumps"], + File["oracle_audit_dumps"], + File["oracle_core_dumps"], + File["oracle_pfile_dir"], + File["oracle_dumps_${oracle_sid}"] + ] , + mode => 755 + } + + oracle_dir { + "oracle_dumps_${oracle_sid}": + path => "/logs/oracle/oradumps/${oracle_sid}", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps"], + before => [ + File["oracle_user_dumps"], + File["oracle_background_dumps"], + File["oracle_audit_dumps"], + File["oracle_core_dumps"], + File["oracle_pfile_dir"] + ], + mode => 755 + } + + oracle_dir { + "oracle_user_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/udump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_background_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/bdump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_audit_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/adump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_core_dumps": + path => "/logs/oracle/oradumps/${oracle_sid}/cdump", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } + + oracle_dir { + "oracle_pfile_dir": + path => "/logs/oracle/oradumps/${oracle_sid}/pfile", + ensure => directory, + owner => "oracle", + group => "dba", + require => File["oracle_dumps_${oracle_sid}"], + mode => 755 + } } define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } }
jeremybaumont/Oracle-puppet-module
5122bd6ec2044344d70923c6e3c5230ea769a289
add GPGv3 license header on top of files
diff --git a/fileserver.conf b/fileserver.conf index 19cccda..dfa6663 100644 --- a/fileserver.conf +++ b/fileserver.conf @@ -1,17 +1,33 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# # This file consists of arbitrarily named sections/modules # defining where files are served from and to whom # Define a section 'files' # Adapt the allow/deny settings to your needs. Order # for allow/deny does not matter, allow always takes precedence # over deny [files] path /etc/puppet/files # allow *.example.com # deny *.evil.example.com # allow 192.168.0.0/24 [plugins] # allow *.example.com # deny *.evil.example.com # allow 192.168.0.0/24 diff --git a/manifests/classes/baseapps.pp b/manifests/classes/baseapps.pp index 93f724e..5086048 100644 --- a/manifests/classes/baseapps.pp +++ b/manifests/classes/baseapps.pp @@ -1,20 +1,36 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class baseapps { case $operatingsystem { solaris: { $packagelist = ["vim","perl", "rubygems"] $provider = "sunfreeware" } default: { fail ( "The operating system $operatingsystem is not yet supported by baseapps class") } } package { $packagelist: ensure => installed, provider => $provider } } diff --git a/manifests/classes/solaris.pp b/manifests/classes/solaris.pp index 871461a..39ee378 100644 --- a/manifests/classes/solaris.pp +++ b/manifests/classes/solaris.pp @@ -1,3 +1,19 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class solaris { } diff --git a/manifests/groups/virt_groups.pp b/manifests/groups/virt_groups.pp index e9cc150..0ca6116 100644 --- a/manifests/groups/virt_groups.pp +++ b/manifests/groups/virt_groups.pp @@ -1,3 +1,19 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class virt_groups { } diff --git a/manifests/nodes.pp b/manifests/nodes.pp index 8706298..04479c0 100644 --- a/manifests/nodes.pp +++ b/manifests/nodes.pp @@ -1,11 +1,27 @@ +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + node 'jeremy-test.wanadoo.nl' { $architecture = "sparc64" $oracle_major_version = "10g" $operatingsystem = "solaris" $oracle_version = "10.2.0.4" $oracle_patch_version = "earth" include oracle::database_server } diff --git a/manifests/site.pp b/manifests/site.pp index 1d39e3c..ffeb27a 100644 --- a/manifests/site.pp +++ b/manifests/site.pp @@ -1,14 +1,30 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# import "templates.pp" import "classes/*" import "groups/*" import "users/*" import "oracle" import "oracle/*.pp" import "nodes.pp" filebucket { main: server => puppet } File { backup => main } diff --git a/manifests/templates.pp b/manifests/templates.pp index 8f1a704..74d27bd 100644 --- a/manifests/templates.pp +++ b/manifests/templates.pp @@ -1,14 +1,30 @@ +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + node basenode { case $operatingsystem { solaris: { include solaris } default: { include solaris } } include baseapps } node default inherits basenode{} node oracle_database_server inherits basenode { include oracle_database_server, oracle_administrators } diff --git a/manifests/users/virt_users.pp b/manifests/users/virt_users.pp index 5ccb585..22be513 100644 --- a/manifests/users/virt_users.pp +++ b/manifests/users/virt_users.pp @@ -1,4 +1,20 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class virt_users { } diff --git a/modules/oracle/manifests/administrators.pp b/modules/oracle/manifests/administrators.pp index f0810da..f3a5b5a 100644 --- a/modules/oracle/manifests/administrators.pp +++ b/modules/oracle/manifests/administrators.pp @@ -1,9 +1,25 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class oracle::administrators { include oracle::virt_users, oracle::virt_groups realize( Group["dba"], Group["oinstall"], User["oracle"] ) } diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 7482493..d603426 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,139 +1,155 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class oracle::database_server { # required user and groups include oracle::administrators # required packages include oracle::database_server::system_packages # required directories $oracle_base_path = "/opt/applications/oracle" oracle_dir { "oracle_base": path => $oracle_base_path, ensure => directory, owner => "oracle", group => "oinstall", before => [ File["oracle_home"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_major_version": path => "${oracle_base_path}/${oracle_major_version}", ensure => directory, owner => "oracle", group => "oinstall", require => File["oracle_base"], before => [ File["oracle_home"], File["oracle_version"] ], mode => 755 } oracle_dir { "oracle_version": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"] ], before => File["oracle_home"] , mode => 755 } oracle_dir { "oracle_home": path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}", ensure => directory, owner => "oracle", group => "oinstall", require => [ File["oracle_base"], File["oracle_major_version"], File["oracle_version"] ], mode => 755 } } define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { file { $name: path => $path, ensure => $ensure, force => true, owner => $owner, group => $group, recurse => 5, mode => $mode } } class oracle::database_server::system_packages { case $operatingsystem { "solaris": { $sun_provider = "sun" case $oracle_major_version { "10g": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } "9i": { case $architecture { "sparc64": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } "sparc32": { $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] } default: { fail("oracle::database_server - the architecture $architecture is not yet supported by class system_packages.") } } } default: { fail("oracle::database_server - the oracle version $oracle_major_version is not yet support by class system_packages.") } } } default: { fail("oracle::database_server - the operating system $operatingsystem is not yet supported by class system_packages.") } } notify {"oracle::database_server - the operating system is ${operatingsystem}": } notify {"oracle::database_server - the architecture is ${architecture}": } notify {"oracle::database_server - the architecture is ${oracle_major_version}": } notify {"oracle::database_server - the list of packages required is ${system_packages}": } package { $ystem_packages: ensure => installed, provider => $sun_provider } } diff --git a/modules/oracle/manifests/init.pp b/modules/oracle/manifests/init.pp index b9e3346..d376aa0 100644 --- a/modules/oracle/manifests/init.pp +++ b/modules/oracle/manifests/init.pp @@ -1,5 +1,21 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class oracle{ include oracle::database_server } diff --git a/modules/oracle/manifests/virt_groups.pp b/modules/oracle/manifests/virt_groups.pp index 5772d4d..7d95de6 100644 --- a/modules/oracle/manifests/virt_groups.pp +++ b/modules/oracle/manifests/virt_groups.pp @@ -1,12 +1,28 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class oracle::virt_groups { @group { dba: gid => 500, ensure => present, } @group { oinstall: gid => 501, ensure => present, } } diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index f8c830d..7f1ba1a 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,12 +1,28 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# class oracle::virt_users { @user { oracle: ensure => present, uid => 500, gid => 500, comment => "Oracle User", home => "/home/oracle", require => Group["dba"], shell => "/bin/bash", } } diff --git a/puppet.conf b/puppet.conf index 01e92a1..e20038e 100644 --- a/puppet.conf +++ b/puppet.conf @@ -1,10 +1,41 @@ + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +# Copyright (C) 2009 Jeremy Baumont +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. [main] logdir=/var/log/puppet vardir=/var/lib/puppet ssldir=/var/lib/puppet/ssl rundir=/var/run/puppet factpath=$vardir/lib/facter pluginsync=true [puppetmasterd] templatedir=/var/lib/puppet/templates
jeremybaumont/Oracle-puppet-module
4ae3e5f218bd4d54bdca0e2d3449081912407996
add system packages resources and directories resources to oracle datbase_server class
diff --git a/manifests/classes/baseapps.pp b/manifests/classes/baseapps.pp index c10b7c8..93f724e 100644 --- a/manifests/classes/baseapps.pp +++ b/manifests/classes/baseapps.pp @@ -1,8 +1,20 @@ class baseapps { + case $operatingsystem { - $packagelist = ["vi","perl", "rubygems"] + solaris: { + $packagelist = ["vim","perl", "rubygems"] + $provider = "sunfreeware" + } + default: { + fail ( "The operating system $operatingsystem + is not yet supported by baseapps class") + } + } - package { $packagelist: - ensure => installed } + package { + $packagelist: + ensure => installed, + provider => $provider + } } diff --git a/manifests/nodes.pp b/manifests/nodes.pp index 40dc7c8..8706298 100644 --- a/manifests/nodes.pp +++ b/manifests/nodes.pp @@ -1 +1,11 @@ -node 'jeremy-test.wanadoo.nl' inherits oracle_database_server {} + +node 'jeremy-test.wanadoo.nl' { + $architecture = "sparc64" + $oracle_major_version = "10g" + $operatingsystem = "solaris" + $oracle_version = "10.2.0.4" + $oracle_patch_version = "earth" + + include oracle::database_server + +} diff --git a/manifests/site.pp b/manifests/site.pp index 4a99936..1d39e3c 100644 --- a/manifests/site.pp +++ b/manifests/site.pp @@ -1,11 +1,14 @@ import "templates.pp" -import "nodes.pp" import "classes/*" import "groups/*" import "users/*" -#import "os/*" + +import "oracle" +import "oracle/*.pp" + +import "nodes.pp" filebucket { main: server => puppet } File { backup => main } diff --git a/modules/oracle/manifests/administrators.pp b/modules/oracle/manifests/administrators.pp index 90f6e33..f0810da 100644 --- a/modules/oracle/manifests/administrators.pp +++ b/modules/oracle/manifests/administrators.pp @@ -1,9 +1,9 @@ -class administrators { +class oracle::administrators { include oracle::virt_users, oracle::virt_groups realize( Group["dba"], Group["oinstall"], User["oracle"] ) } diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index e0222e0..7482493 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,8 +1,139 @@ -class database_server { +class oracle::database_server { # required user and groups include oracle::administrators # required packages - include oracle::system_packages + include oracle::database_server::system_packages + + # required directories + $oracle_base_path = "/opt/applications/oracle" + oracle_dir { + "oracle_base": + path => $oracle_base_path, + ensure => directory, + owner => "oracle", + group => "oinstall", + before => [ + File["oracle_home"], + File["oracle_major_version"], + File["oracle_version"] + ], + mode => 755 + } + + oracle_dir { + "oracle_major_version": + path => "${oracle_base_path}/${oracle_major_version}", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => File["oracle_base"], + before => [ + File["oracle_home"], + File["oracle_version"] + ], + mode => 755 + } + + oracle_dir { + "oracle_version": + path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => [ + File["oracle_base"], + File["oracle_major_version"] + ], + before => File["oracle_home"] , + mode => 755 + } + + oracle_dir { + "oracle_home": + path => "${oracle_base_path}/${oracle_major_version}/${oracle_version}/${oracle_patch_version}", + ensure => directory, + owner => "oracle", + group => "oinstall", + require => [ + File["oracle_base"], + File["oracle_major_version"], + File["oracle_version"] + ], + mode => 755 + } +} + +define oracle_dir ( $path, $ensure, $owner, $group, $mode ) { + file { + $name: + path => $path, + ensure => $ensure, + force => true, + owner => $owner, + group => $group, + recurse => 5, + mode => $mode + } +} + + + +class oracle::database_server::system_packages { + + case $operatingsystem { + "solaris": { + $sun_provider = "sun" + case $oracle_major_version { + "10g": { + case $architecture { + "sparc64": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt", "SUNWsprox"] + } + "sparc32": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWi1cs", "SUNWi15cs", "SUNWxwfnt"] + } + default: { + fail("oracle::database_server - the architecture $architecture is not + yet supported by class system_packages.") + } + } + } + "9i": { + case $architecture { + "sparc64": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] + } + "sparc32": { + $system_packages = ["SUNWarc", "SUNWbtool", "SUNWhea", "SUNWlibm", "SUNWlibms", "SUNWsprot", "SUNWtoo", "SUNWi1of", "SUNWxwfnt"] + } + + default: { + fail("oracle::database_server - the architecture $architecture is not + yet supported by class system_packages.") + } + } + } + + default: { + fail("oracle::database_server - the oracle version $oracle_major_version is not + yet support by class system_packages.") + } + } + } + default: { + fail("oracle::database_server - the operating system $operatingsystem is not + yet supported by class system_packages.") + } + + } + + notify {"oracle::database_server - the operating system is ${operatingsystem}": } + notify {"oracle::database_server - the architecture is ${architecture}": } + notify {"oracle::database_server - the architecture is ${oracle_major_version}": } + notify {"oracle::database_server - the list of packages required is ${system_packages}": } + + package { $ystem_packages: ensure => installed, provider => $sun_provider } + } diff --git a/modules/oracle/manifests/virt_groups.pp b/modules/oracle/manifests/virt_groups.pp index 94dbeb4..5772d4d 100644 --- a/modules/oracle/manifests/virt_groups.pp +++ b/modules/oracle/manifests/virt_groups.pp @@ -1,12 +1,12 @@ -class virt_groups { +class oracle::virt_groups { @group { dba: gid => 500, ensure => present, } @group { oinstall: gid => 501, ensure => present, } } diff --git a/modules/oracle/manifests/virt_users.pp b/modules/oracle/manifests/virt_users.pp index e17e151..f8c830d 100644 --- a/modules/oracle/manifests/virt_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,12 +1,12 @@ -class virt_users { +class oracle::virt_users { @user { oracle: ensure => present, uid => 500, gid => 500, comment => "Oracle User", home => "/home/oracle", require => Group["dba"], shell => "/bin/bash", } }
jeremybaumont/Oracle-puppet-module
8ede589904674ddaeb7474a5b3c9e57667893220
modify classes names by deleting redundant oracle pattern
diff --git a/modules/oracle/manifests/oracle_administrators.pp b/modules/oracle/manifests/administrators.pp similarity index 54% rename from modules/oracle/manifests/oracle_administrators.pp rename to modules/oracle/manifests/administrators.pp index 4b53830..90f6e33 100644 --- a/modules/oracle/manifests/oracle_administrators.pp +++ b/modules/oracle/manifests/administrators.pp @@ -1,9 +1,9 @@ -class oracle_administrators { - include oracle::virt_oracle_users, oracle::virt_oracle_groups +class administrators { + include oracle::virt_users, oracle::virt_groups realize( Group["dba"], Group["oinstall"], User["oracle"] ) } diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp index 92d584b..e0222e0 100644 --- a/modules/oracle/manifests/database_server.pp +++ b/modules/oracle/manifests/database_server.pp @@ -1,3 +1,8 @@ class database_server { - include oracle::oracle_administrator + + # required user and groups + include oracle::administrators + + # required packages + include oracle::system_packages } diff --git a/modules/oracle/manifests/init.pp b/modules/oracle/manifests/init.pp index e69de29..b9e3346 100644 --- a/modules/oracle/manifests/init.pp +++ b/modules/oracle/manifests/init.pp @@ -0,0 +1,5 @@ +class oracle{ + + include oracle::database_server + +} diff --git a/modules/oracle/manifests/virt_oracle_groups.pp b/modules/oracle/manifests/virt_groups.pp similarity index 85% rename from modules/oracle/manifests/virt_oracle_groups.pp rename to modules/oracle/manifests/virt_groups.pp index 310ac11..94dbeb4 100644 --- a/modules/oracle/manifests/virt_oracle_groups.pp +++ b/modules/oracle/manifests/virt_groups.pp @@ -1,12 +1,12 @@ -class virt_oracle_groups { +class virt_groups { @group { dba: gid => 500, ensure => present, } @group { oinstall: gid => 501, ensure => present, } } diff --git a/modules/oracle/manifests/virt_oracle_users.pp b/modules/oracle/manifests/virt_users.pp similarity index 89% rename from modules/oracle/manifests/virt_oracle_users.pp rename to modules/oracle/manifests/virt_users.pp index 8908c96..e17e151 100644 --- a/modules/oracle/manifests/virt_oracle_users.pp +++ b/modules/oracle/manifests/virt_users.pp @@ -1,12 +1,12 @@ -class virt_oracle_users { +class virt_users { @user { oracle: ensure => present, uid => 500, gid => 500, comment => "Oracle User", home => "/home/oracle", require => Group["dba"], shell => "/bin/bash", } }
jeremybaumont/Oracle-puppet-module
d6991b6266965cb6403161617f23c4cff7a21665
modify namespace of users and groups classes to take in account modularized configuration of oracle
diff --git a/modules/oracle/manifests/oracle_administrators.pp b/modules/oracle/manifests/oracle_administrators.pp index 177d877..4b53830 100644 --- a/modules/oracle/manifests/oracle_administrators.pp +++ b/modules/oracle/manifests/oracle_administrators.pp @@ -1,9 +1,9 @@ class oracle_administrators { - include virt_oracle_users, virt_oracle_groups + include oracle::virt_oracle_users, oracle::virt_oracle_groups realize( Group["dba"], Group["oinstall"], User["oracle"] ) }
jeremybaumont/Oracle-puppet-module
1e8f4d991a29d2322d13312776d98e67f17073cd
rename oracle_database_server class to database_server
diff --git a/modules/oracle/manifests/database_server.pp b/modules/oracle/manifests/database_server.pp new file mode 100644 index 0000000..92d584b --- /dev/null +++ b/modules/oracle/manifests/database_server.pp @@ -0,0 +1,3 @@ +class database_server { + include oracle::oracle_administrator +} diff --git a/modules/oracle/manifests/oracle_database_server.pp b/modules/oracle/manifests/oracle_database_server.pp deleted file mode 100644 index e27d11c..0000000 --- a/modules/oracle/manifests/oracle_database_server.pp +++ /dev/null @@ -1,3 +0,0 @@ -class oracle_database_server { - -}
jeremybaumont/Oracle-puppet-module
3f4bdf9bd3250e571f463ebceaed503fac9095e6
delete inheritance of virt_groups and virt_users classes
diff --git a/modules/oracle/manifests/virt_oracle_groups.pp b/modules/oracle/manifests/virt_oracle_groups.pp index 484f627..310ac11 100644 --- a/modules/oracle/manifests/virt_oracle_groups.pp +++ b/modules/oracle/manifests/virt_oracle_groups.pp @@ -1,12 +1,12 @@ -class virt_oracle_groups inherits virt_groups { +class virt_oracle_groups { @group { dba: - gid => 200, + gid => 500, ensure => present, } @group { oinstall: - gid => 201, + gid => 501, ensure => present, } } diff --git a/modules/oracle/manifests/virt_oracle_users.pp b/modules/oracle/manifests/virt_oracle_users.pp index 0a15133..8908c96 100644 --- a/modules/oracle/manifests/virt_oracle_users.pp +++ b/modules/oracle/manifests/virt_oracle_users.pp @@ -1,12 +1,12 @@ -class virt_oracle_users inherits virt_users { +class virt_oracle_users { @user { oracle: ensure => present, - uid => 200, - gid => 200, + uid => 500, + gid => 500, comment => "Oracle User", home => "/home/oracle", require => Group["dba"], shell => "/bin/bash", } }
jeremybaumont/Oracle-puppet-module
bf3c8563b5e854d68bca1788f9c9da319649906c
modularized oracle manifests
diff --git a/modules/oracle/manifests/init.pp b/modules/oracle/manifests/init.pp new file mode 100644 index 0000000..e69de29 diff --git a/modules/oracle/manifests/oracle_administrators.pp b/modules/oracle/manifests/oracle_administrators.pp new file mode 100644 index 0000000..177d877 --- /dev/null +++ b/modules/oracle/manifests/oracle_administrators.pp @@ -0,0 +1,9 @@ +class oracle_administrators { + include virt_oracle_users, virt_oracle_groups + + realize( + Group["dba"], + Group["oinstall"], + User["oracle"] + ) +} diff --git a/modules/oracle/manifests/oracle_database_server.pp b/modules/oracle/manifests/oracle_database_server.pp new file mode 100644 index 0000000..e27d11c --- /dev/null +++ b/modules/oracle/manifests/oracle_database_server.pp @@ -0,0 +1,3 @@ +class oracle_database_server { + +} diff --git a/modules/oracle/manifests/virt_oracle_groups.pp b/modules/oracle/manifests/virt_oracle_groups.pp new file mode 100644 index 0000000..484f627 --- /dev/null +++ b/modules/oracle/manifests/virt_oracle_groups.pp @@ -0,0 +1,12 @@ +class virt_oracle_groups inherits virt_groups { + + @group { dba: + gid => 200, + ensure => present, + } + + @group { oinstall: + gid => 201, + ensure => present, + } +} diff --git a/modules/oracle/manifests/virt_oracle_users.pp b/modules/oracle/manifests/virt_oracle_users.pp new file mode 100644 index 0000000..0a15133 --- /dev/null +++ b/modules/oracle/manifests/virt_oracle_users.pp @@ -0,0 +1,12 @@ +class virt_oracle_users inherits virt_users { + + @user { oracle: + ensure => present, + uid => 200, + gid => 200, + comment => "Oracle User", + home => "/home/oracle", + require => Group["dba"], + shell => "/bin/bash", + } +}
jeremybaumont/Oracle-puppet-module
dafd1556c11567e7c557236ead1448dfb3379a0e
initial import
diff --git a/fileserver.conf b/fileserver.conf new file mode 100644 index 0000000..19cccda --- /dev/null +++ b/fileserver.conf @@ -0,0 +1,17 @@ +# This file consists of arbitrarily named sections/modules +# defining where files are served from and to whom + +# Define a section 'files' +# Adapt the allow/deny settings to your needs. Order +# for allow/deny does not matter, allow always takes precedence +# over deny +[files] + path /etc/puppet/files +# allow *.example.com +# deny *.evil.example.com +# allow 192.168.0.0/24 + +[plugins] +# allow *.example.com +# deny *.evil.example.com +# allow 192.168.0.0/24 diff --git a/manifests/classes/baseapps.pp b/manifests/classes/baseapps.pp new file mode 100644 index 0000000..c10b7c8 --- /dev/null +++ b/manifests/classes/baseapps.pp @@ -0,0 +1,8 @@ +class baseapps { + + $packagelist = ["vi","perl", "rubygems"] + + package { $packagelist: + ensure => installed } + +} diff --git a/manifests/classes/oracle_database_server.pp b/manifests/classes/oracle_database_server.pp new file mode 100644 index 0000000..e27d11c --- /dev/null +++ b/manifests/classes/oracle_database_server.pp @@ -0,0 +1,3 @@ +class oracle_database_server { + +} diff --git a/manifests/classes/solaris.pp b/manifests/classes/solaris.pp new file mode 100644 index 0000000..871461a --- /dev/null +++ b/manifests/classes/solaris.pp @@ -0,0 +1,3 @@ +class solaris { + +} diff --git a/manifests/groups/virt_groups.pp b/manifests/groups/virt_groups.pp new file mode 100644 index 0000000..e9cc150 --- /dev/null +++ b/manifests/groups/virt_groups.pp @@ -0,0 +1,3 @@ +class virt_groups { + +} diff --git a/manifests/groups/virt_oracle_groups.pp b/manifests/groups/virt_oracle_groups.pp new file mode 100644 index 0000000..484f627 --- /dev/null +++ b/manifests/groups/virt_oracle_groups.pp @@ -0,0 +1,12 @@ +class virt_oracle_groups inherits virt_groups { + + @group { dba: + gid => 200, + ensure => present, + } + + @group { oinstall: + gid => 201, + ensure => present, + } +} diff --git a/manifests/nodes.pp b/manifests/nodes.pp new file mode 100644 index 0000000..40dc7c8 --- /dev/null +++ b/manifests/nodes.pp @@ -0,0 +1 @@ +node 'jeremy-test.wanadoo.nl' inherits oracle_database_server {} diff --git a/manifests/site.pp b/manifests/site.pp new file mode 100644 index 0000000..4a99936 --- /dev/null +++ b/manifests/site.pp @@ -0,0 +1,11 @@ +import "templates.pp" +import "nodes.pp" +import "classes/*" +import "groups/*" +import "users/*" +#import "os/*" + +filebucket { main: server => puppet } +File { backup => main } + + diff --git a/manifests/templates.pp b/manifests/templates.pp new file mode 100644 index 0000000..8f1a704 --- /dev/null +++ b/manifests/templates.pp @@ -0,0 +1,14 @@ + +node basenode { + case $operatingsystem { + solaris: { include solaris } + default: { include solaris } + } + include baseapps +} + +node default inherits basenode{} + +node oracle_database_server inherits basenode { + include oracle_database_server, oracle_administrators +} diff --git a/manifests/users/oracle_administrators.pp b/manifests/users/oracle_administrators.pp new file mode 100644 index 0000000..177d877 --- /dev/null +++ b/manifests/users/oracle_administrators.pp @@ -0,0 +1,9 @@ +class oracle_administrators { + include virt_oracle_users, virt_oracle_groups + + realize( + Group["dba"], + Group["oinstall"], + User["oracle"] + ) +} diff --git a/manifests/users/virt_oracle_users.pp b/manifests/users/virt_oracle_users.pp new file mode 100644 index 0000000..0a15133 --- /dev/null +++ b/manifests/users/virt_oracle_users.pp @@ -0,0 +1,12 @@ +class virt_oracle_users inherits virt_users { + + @user { oracle: + ensure => present, + uid => 200, + gid => 200, + comment => "Oracle User", + home => "/home/oracle", + require => Group["dba"], + shell => "/bin/bash", + } +} diff --git a/manifests/users/virt_users.pp b/manifests/users/virt_users.pp new file mode 100644 index 0000000..5ccb585 --- /dev/null +++ b/manifests/users/virt_users.pp @@ -0,0 +1,4 @@ +class virt_users { + + +} diff --git a/puppet.conf b/puppet.conf new file mode 100644 index 0000000..01e92a1 --- /dev/null +++ b/puppet.conf @@ -0,0 +1,10 @@ +[main] +logdir=/var/log/puppet +vardir=/var/lib/puppet +ssldir=/var/lib/puppet/ssl +rundir=/var/run/puppet +factpath=$vardir/lib/facter +pluginsync=true + +[puppetmasterd] +templatedir=/var/lib/puppet/templates
Br3nda/drupal-module-project_issue
4cb78ef969be37125c44e658e3cc3a672e4582c8
#934030 by drumm, dww: Add a blank slate for the 'Issue cockpit' in homebox.
diff --git a/project_issue.module b/project_issue.module index ddffb62..a3c25e7 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.186 2010/10/01 21:50:23 dww Exp $ +// $Id: project_issue.module,v 1.187 2010/10/09 00:31:31 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } /** * Implementation of hook_ctools_plugin_directory(). */ function project_issue_ctools_plugin_directory($module, $plugin) { if ($module == 'sampler') { switch ($plugin) { case 'metric': return 'metrics'; } } } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); @@ -1258,654 +1258,662 @@ function project_issue_requirements($phase) { if ($phase == 'runtime') { $grants = module_implements('node_grants'); $allowed_roles = user_roles(FALSE, 'access project issues'); $conflict_anonymous = empty($allowed_roles[DRUPAL_ANONYMOUS_RID]); foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if (!empty($grants) && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { if (isset($result->project_issues_sid)) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; } if (isset($result->project_issues_priority)) { $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( - 'info' => t('Issue cockpit'), + 'info' => t('Project Issue Summary'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view') { - if (isset($edit['homebox']) && isset($edit['homebox']->nid)) { - // Homebox provides stored configuration in $edit. - $node = node_load($edit['homebox']->nid); + if (isset($edit['homebox'])) { + if (isset($edit['homebox']->nid)) { + // Homebox provides stored configuration in $edit. + $node = node_load($edit['homebox']->nid); + } + else { + return array( + 'subject' => t('Issues for ...'), + 'content' => t('<a href="javascript:void(0)" class="portlet-settings">Configure</a> to select a project.'), + ); + } } else { // Otherwise check if we are on a project page. $node = project_get_project_from_menu(); } if (!empty($node) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } } /** * Provide a list of keys Homebox will store. */ function project_issue_homebox_block_keys($block) { return array('nid'); } /** * Provide an edit form specific to homebox blocks. * * Allows switching what project is used. */ function project_issue_homebox_block_edit_form($block) { $form = array(); $node = node_load($block->nid); $form['project_title'] = array( '#type' => 'textfield', '#title' => t('Project name'), '#size' => 20, '#autocomplete_path' => 'project/autocomplete/project', '#default_value' => empty($node) ? '' : $node->title, ); $form['#validate'][] = 'project_issue_homebox_block_edit_form_validate'; return $form; } /** * Validation callback for editing the project issue cockpit block via homebox. * * Makes sure a valid project title was entered and populates the nid. The nid * is automatically saved by homebox if it's in $form_state['values'] so * there's no need for a submit callback. */ function project_issue_homebox_block_edit_form_validate($form, &$form_state) { $nid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_title'], 'project_project')); if (empty($nid)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } else { $form_state['values']['nid'] = $nid; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } } /** * Implementation of hook_views_post_render(). */ function project_issue_views_post_render(&$view, &$output, &$cache) { // Add links to the top of the project_issue views. $my_projects_views = variable_get('project_issue_my_projects_views', array('project_issue_user_projects')); if (in_array($view->name, $my_projects_views)) { // Tack the "my projects" table onto the user projects view. if ($view->current_display == 'page_1') { $output = project_issue_my_projects_table() . $output; } } // Add links to the issue queue views. $query_link_views = variable_get('project_issue_query_link_views', array('project_issue_all_projects', 'project_issue_project', 'project_issue_search_all', 'project_issue_search_project', 'project_issue_user_issues')); if (in_array($view->name, $query_link_views)) { if ($view->current_display == 'page_1') { $arg = NULL; if (isset($view->argument['pid'])) { $arg = $view->argument['pid']->get_value(); } $output = project_issue_query_result_links($arg) . $output; } } } /** * Preprocess function for the comment theme template. * * This enforces the 'project_issue_show_comment_signatures' setting. */ function project_issue_preprocess_comment(&$variables) { if (!variable_get('project_issue_show_comment_signatures', 0)) { $variables['signature'] = ''; } }
Br3nda/drupal-module-project_issue
2d9d2f94105d8e69344e4a4b74453cc694c2ee52
#932376 by dww: Fixed bug that could cross-pollinate default issue views and inject bogus sorts and filters into each other (made worse by [#921210]).
diff --git a/views/default_views/project_issue_all_projects.view.php b/views/default_views/project_issue_all_projects.view.php index a851405..dcc01d4 100644 --- a/views/default_views/project_issue_all_projects.view.php +++ b/views/default_views/project_issue_all_projects.view.php @@ -1,432 +1,434 @@ <?php -// $Id: project_issue_all_projects.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ +// $Id: project_issue_all_projects.view.php,v 1.3 2010/10/05 17:12:43 dww Exp $ /** * @file * Issue queue across all projects. */ $view = new view; $view->name = 'project_issue_all_projects'; $view->description = 'Project issues for all projects'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); +$sorts = array(); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'all', 'project_uid_argument' => '', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { + $search_filter = array(); $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Issues for all projects'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Issues', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/rss'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_project.view.php b/views/default_views/project_issue_project.view.php index d077d4e..969feab 100644 --- a/views/default_views/project_issue_project.view.php +++ b/views/default_views/project_issue_project.view.php @@ -1,583 +1,585 @@ <?php -// $Id: project_issue_project.view.php,v 1.3 2010/10/05 00:44:31 dww Exp $ +// $Id: project_issue_project.view.php,v 1.4 2010/10/05 17:12:43 dww Exp $ /** * @file * Issue queue for a specific project. */ $view = new view; $view->name = 'project_issue_project'; $view->description = 'Project issues by project'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), )); $fields = array( 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'component' => array( 'label' => 'Component', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'not found', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'title' => 'Issues for %1', 'default_argument_type' => 'fixed', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', ), )); +$sorts = array(); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'rid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'rid_op', 'identifier' => 'version', 'label' => 'Version', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'component' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'component_op', 'identifier' => 'component', 'label' => 'Component', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), ); if (module_exists('search')) { + $search_filter = array(); $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Issues by project'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'component' => 'component', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'component' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => '0', 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/rss/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('title', 'Recent issues'); $handler->override_option('relationships', array()); $handler->override_option('fields', array( 'title' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', 'override' => array( 'button' => 'Use default', ), ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), )); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'default_argument_type' => 'node', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array(), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => FALSE, 'expose' => array(), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), )); $handler->override_option('empty', 'No open issues.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 5); $handler->override_option('use_pager', '0'); $handler->override_option('style_plugin', 'list'); $handler->override_option('style_options', array( 'grouping' => '', 'type' => 'ul', )); $handler->override_option('row_options', array( 'inline' => array( 'title' => 'title', 'timestamp' => 'timestamp', ), 'separator' => ' ', )); $handler->override_option('block_description', 'Project: recent issues'); $handler->override_option('block_caching', -1); diff --git a/views/default_views/project_issue_search_all.view.php b/views/default_views/project_issue_search_all.view.php index 28bb68f..37e04ee 100644 --- a/views/default_views/project_issue_search_all.view.php +++ b/views/default_views/project_issue_search_all.view.php @@ -1,503 +1,505 @@ <?php -// $Id: project_issue_search_all.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ +// $Id: project_issue_search_all.view.php,v 1.3 2010/10/05 17:12:43 dww Exp $ /** * @file * Advanced issue search for all projects. */ $view = new view; $view->name = 'project_issue_search_all'; $view->description = 'Project issue advanced search for all projects'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'search', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); +$sorts = array(); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'all', 'project_uid_argument' => '', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'uid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_op', 'identifier' => 'assigned', 'label' => 'Assigned', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid', 'table' => 'users', 'field' => 'uid', 'relationship' => 'assigned', ), 'uid_1' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_1_op', 'identifier' => 'submitted', 'label' => 'Submitted by', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_1', 'table' => 'users', 'field' => 'uid', 'relationship' => 'none', ), 'uid_touch' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_touch_op', 'identifier' => 'participant', 'label' => 'Participant', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { + $search_filter = array(); $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } _project_issue_views_add_taxonomy_filters($filters); $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Search issues for all projects'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/search'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Advanced search', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/search/rss'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_search_project.view.php b/views/default_views/project_issue_search_project.view.php index 28785ef..cfd8c86 100644 --- a/views/default_views/project_issue_search_project.view.php +++ b/views/default_views/project_issue_search_project.view.php @@ -1,557 +1,559 @@ <?php -// $Id: project_issue_search_project.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ +// $Id: project_issue_search_project.view.php,v 1.3 2010/10/05 17:12:43 dww Exp $ /** * @file * Advanced issue search for a specific project. */ $view = new view; $view->name = 'project_issue_search_project'; $view->description = 'Project issue advanced search for specific projects'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'component' => array( 'label' => 'Component', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'not found', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'title' => 'Search issues for %1', 'default_argument_type' => 'fixed', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_argument_node_type' => array(), 'validate_argument_node_access' => 0, 'validate_argument_nid_type' => 'nid', 'validate_argument_vocabulary' => array(), 'validate_argument_type' => 'tid', 'validate_argument_project_term_vocabulary' => array( '1' => 0, ), 'validate_argument_project_term_argument_type' => 'tid', 'validate_argument_project_term_argument_action_top_without' => 'pass', 'validate_argument_project_term_argument_action_top_with' => 'pass', 'validate_argument_project_term_argument_action_child' => 'pass', 'validate_argument_php' => '', ), )); +$sorts = array(); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'uid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_op', 'identifier' => 'assigned', 'label' => 'Assigned', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid', 'table' => 'users', 'field' => 'uid', 'relationship' => 'assigned', ), 'uid_1' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_1_op', 'identifier' => 'submitted', 'label' => 'Submitted by', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_1', 'table' => 'users', 'field' => 'uid', 'relationship' => 'none', ), 'uid_touch' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_touch_op', 'identifier' => 'participant', 'label' => 'Participant', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'rid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'rid_op', 'identifier' => 'version', 'label' => 'Version', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'component' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'component_op', 'identifier' => 'component', 'label' => 'Component', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), ); if (module_exists('search')) { + $search_filter = array(); $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } _project_issue_views_add_taxonomy_filters($filters); $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Search issues for a project'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'component' => 'component', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'component' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/search/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => 'Advanced search', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/search/%/rss'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_user_issues.view.php b/views/default_views/project_issue_user_issues.view.php index 96a25a7..571e060 100644 --- a/views/default_views/project_issue_user_issues.view.php +++ b/views/default_views/project_issue_user_issues.view.php @@ -1,605 +1,606 @@ <?php -// $Id: project_issue_user_issues.view.php,v 1.4 2010/10/04 19:49:51 dww Exp $ +// $Id: project_issue_user_issues.view.php,v 1.5 2010/10/05 17:12:43 dww Exp $ /** * @file * All issues a user has created or commented on. */ $view = new view; $view->name = 'project_issue_user_issues'; $view->description = 'Project issues for a specific user'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => '', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), ); if (function_exists('tracker2_views_api')) { $last_update_field = 'changed'; $fields['changed'] = array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'changed', 'table' => 'tracker2_user', 'field' => 'changed', 'relationship' => 'none', ); } else { $last_update_field = 'last_comment_timestamp'; $fields['last_comment_timestamp'] = array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); } $fields['name'] = array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => $last_update_field, 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'uid_touch' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => 'all', 'wildcard_substitution' => 'All', 'title' => 'Issues for %1', 'default_argument_type' => 'current_user', 'default_argument' => '', 'validate_type' => 'user', 'validate_fail' => 'not found', 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_user_argument_type' => 'either', 'validate_user_restrict_roles' => 1, 'validate_user_roles' => array('2' => 2), ), )); $last_update_sort = array(); if (function_exists('tracker2_views_api')) { $last_update_sort['changed'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'changed', 'table' => 'tracker2_user', 'field' => 'changed', 'relationship' => 'none', ); } else { $last_update_sort['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); } $sorts = $last_update_sort; if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'participant', 'project_uid_argument' => 'uid_touch', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); $published_filter = array(); if (function_exists('tracker2_views_api')) { $published_filter['published'] = array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'published', 'table' => 'tracker2_user', 'field' => 'published', 'relationship' => 'none', ); } else { $published_filter['status_extra'] = array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ); } $filters = $published_filter + $filters; if (module_exists('search')) { + $search_filter = array(); $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'project_issue_access_per_user_queue', 'project_issue_user_argument' => 'uid_touch', )); $handler->override_option('title', 'My issues'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', $last_update_field => $last_update_field, 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), $last_update_field => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : $last_update_field, )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/user'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My issues', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/user/%/feed'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('relationships', array( 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $handler->override_option('fields', array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'sid' => array( 'label' => 'Status', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('sorts', $last_update_sort); $handler->override_option('filters', $published_filter); $handler->override_option('items_per_page', 15); $handler->override_option('use_pager', '0'); $handler->override_option('use_more', 1); $handler->override_option('use_more_always', 0); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'sid' => 'sid', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 0, 'separator' => '', ), 'title' => array( 'sortable' => 0, 'separator' => '', ), 'sid' => array( 'sortable' => 0, 'separator' => '', ), ), 'default' => '-1', )); $handler->override_option('block_description', ''); $handler->override_option('block_caching', -1); diff --git a/views/default_views/project_issue_user_projects.view.php b/views/default_views/project_issue_user_projects.view.php index 631950b..55c0d49 100644 --- a/views/default_views/project_issue_user_projects.view.php +++ b/views/default_views/project_issue_user_projects.view.php @@ -1,464 +1,466 @@ <?php -// $Id: project_issue_user_projects.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ +// $Id: project_issue_user_projects.view.php,v 1.3 2010/10/05 17:12:43 dww Exp $ /** * @file * Issues across all projects owned by a user. */ $view = new view; $view->name = 'project_issue_user_projects'; $view->description = "Project issues for a specific user's projects"; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => '', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); +$sorts = array(); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $handler->override_option('arguments', array( 'uid' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => 'all', 'wildcard_substitution' => 'All', 'title' => 'Projects by %1', 'default_argument_type' => 'current_user', 'default_argument' => '', 'validate_type' => 'user', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'uid', 'table' => 'users', 'field' => 'uid', 'relationship' => 'pid', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_user_argument_type' => 'either', 'validate_user_restrict_roles' => 1, 'validate_user_roles' => array('2' => 2), ), )); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'select', 'project_source' => 'owner', 'project_uid_argument' => 'uid', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { + $search_filter = array(); $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'project_issue_access_per_user_queue', 'project_issue_user_argument' => 'uid', )); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/user'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My projects', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('row_options', array( 'item_length' => 'default', )); $handler->override_option('path', 'project/user/%/feed'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE);
Br3nda/drupal-module-project_issue
9c2b1644be09ce8b5412c13c51802efdfe990b04
#930664 by dww: Fixed the empty text on the 'Recent issues' block.
diff --git a/views/default_views/project_issue_project.view.php b/views/default_views/project_issue_project.view.php index 424ac10..d077d4e 100644 --- a/views/default_views/project_issue_project.view.php +++ b/views/default_views/project_issue_project.view.php @@ -1,581 +1,583 @@ <?php -// $Id: project_issue_project.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ +// $Id: project_issue_project.view.php,v 1.3 2010/10/05 00:44:31 dww Exp $ /** * @file * Issue queue for a specific project. */ $view = new view; $view->name = 'project_issue_project'; $view->description = 'Project issues by project'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), )); $fields = array( 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'component' => array( 'label' => 'Component', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'not found', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'title' => 'Issues for %1', 'default_argument_type' => 'fixed', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', ), )); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'rid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'rid_op', 'identifier' => 'version', 'label' => 'Version', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'component' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'component_op', 'identifier' => 'component', 'label' => 'Component', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Issues by project'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'component' => 'component', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'component' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => '0', 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/rss/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('title', 'Recent issues'); $handler->override_option('relationships', array()); $handler->override_option('fields', array( 'title' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', 'override' => array( 'button' => 'Use default', ), ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), )); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'default_argument_type' => 'node', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array(), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => FALSE, 'expose' => array(), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), )); +$handler->override_option('empty', 'No open issues.'); +$handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 5); $handler->override_option('use_pager', '0'); $handler->override_option('style_plugin', 'list'); $handler->override_option('style_options', array( 'grouping' => '', 'type' => 'ul', )); $handler->override_option('row_options', array( 'inline' => array( 'title' => 'title', 'timestamp' => 'timestamp', ), 'separator' => ' ', )); $handler->override_option('block_description', 'Project: recent issues'); $handler->override_option('block_caching', -1);
Br3nda/drupal-module-project_issue
9cd8f5ffa438a210ed57a9f3f0f03ea6b8026c09
#921210 by dww, nnewton: Optimize 'My issues' query using Tracker2 (#928110).
diff --git a/views/default_views/project_issue_user_issues.view.php b/views/default_views/project_issue_user_issues.view.php index 210fd78..96a25a7 100644 --- a/views/default_views/project_issue_user_issues.view.php +++ b/views/default_views/project_issue_user_issues.view.php @@ -1,579 +1,605 @@ <?php -// $Id: project_issue_user_issues.view.php,v 1.3 2010/10/02 23:12:12 dww Exp $ +// $Id: project_issue_user_issues.view.php,v 1.4 2010/10/04 19:49:51 dww Exp $ /** * @file * All issues a user has created or commented on. */ $view = new view; $view->name = 'project_issue_user_issues'; $view->description = 'Project issues for a specific user'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => '', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), - 'last_comment_timestamp' => array( +); +if (function_exists('tracker2_views_api')) { + $last_update_field = 'changed'; + $fields['changed'] = array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'changed', + 'table' => 'tracker2_user', + 'field' => 'changed', + 'relationship' => 'none', + ); +} +else { + $last_update_field = 'last_comment_timestamp'; + $fields['last_comment_timestamp'] = array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), + ); +} +$fields['name'] = array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', + 'alternate_sort' => $last_update_field, 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'uid_touch' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => 'all', 'wildcard_substitution' => 'All', 'title' => 'Issues for %1', 'default_argument_type' => 'current_user', 'default_argument' => '', 'validate_type' => 'user', 'validate_fail' => 'not found', 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_user_argument_type' => 'either', 'validate_user_restrict_roles' => 1, 'validate_user_roles' => array('2' => 2), ), )); -$sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', -); +$last_update_sort = array(); +if (function_exists('tracker2_views_api')) { + $last_update_sort['changed'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'changed', + 'table' => 'tracker2_user', + 'field' => 'changed', + 'relationship' => 'none', + ); +} +else { + $last_update_sort['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ); +} +$sorts = $last_update_sort; if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'participant', 'project_uid_argument' => 'uid_touch', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); +$published_filter = array(); +if (function_exists('tracker2_views_api')) { + $published_filter['published'] = array( + 'operator' => '=', + 'value' => '1', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'published', + 'table' => 'tracker2_user', + 'field' => 'published', + 'relationship' => 'none', + ); +} +else { + $published_filter['status_extra'] = array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ); +} +$filters = $published_filter + $filters; if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'project_issue_access_per_user_queue', 'project_issue_user_argument' => 'uid_touch', )); $handler->override_option('title', 'My issues'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', + $last_update_field => $last_update_field, 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), - 'last_comment_timestamp' => array( + $last_update_field => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', + 'default' => module_exists('search') ? 'score' : $last_update_field, )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/user'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My issues', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/user/%/feed'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('relationships', array( 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $handler->override_option('fields', array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'sid' => array( 'label' => 'Status', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); -$handler->override_option('sorts', array( - 'last_comment_timestamp' => array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), -)); -$handler->override_option('filters', array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), -)); +$handler->override_option('sorts', $last_update_sort); +$handler->override_option('filters', $published_filter); $handler->override_option('items_per_page', 15); $handler->override_option('use_pager', '0'); $handler->override_option('use_more', 1); $handler->override_option('use_more_always', 0); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'sid' => 'sid', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 0, 'separator' => '', ), 'title' => array( 'sortable' => 0, 'separator' => '', ), 'sid' => array( 'sortable' => 0, 'separator' => '', ), ), 'default' => '-1', )); $handler->override_option('block_description', ''); $handler->override_option('block_caching', -1);
Br3nda/drupal-module-project_issue
4a4a019c64fbb05aab069750d162232d69019f7a
#930610 by dww: Made the file scan for default views more restrictive.
diff --git a/views/project_issue.views_default.inc b/views/project_issue.views_default.inc index 9e17ec1..7e1273f 100644 --- a/views/project_issue.views_default.inc +++ b/views/project_issue.views_default.inc @@ -1,72 +1,72 @@ <?php -// $Id: project_issue.views_default.inc,v 1.49 2010/02/18 00:34:30 dww Exp $ +// $Id: project_issue.views_default.inc,v 1.50 2010/10/03 22:53:53 dww Exp $ /** * @file * Provides default views on behalf of the project_issue module. */ /** * Implementation of hook_views_default_views(). */ function project_issue_views_default_views() { // Search the "default_views" directory for files ending in .view.php. - $files = file_scan_directory(drupal_get_path('module', 'project_issue'). '/views/default_views', 'view.php'); + $files = file_scan_directory(drupal_get_path('module', 'project_issue'). '/views/default_views', 'view\.php$'); foreach ($files as $absolute => $file) { // This is not require_once because it's possible that // hook_views_default_views() gets called more than once. require $absolute; if (isset($view)) { // $file->name has the ".php" stripped off, but still has the ".view". $view_name = substr($file->name, 0, strrpos($file->name, '.')); $views[$view_name] = $view; } } return $views; } /** * Add exposed filters for every taxonomy vocabulary for project_issue nodes. * * This is a helper function used by a few of the default view definitions. */ function _project_issue_views_add_taxonomy_filters(&$filters) { if (!module_exists('taxonomy')) { return; } $issue_vocabularies = taxonomy_get_vocabularies('project_issue'); $i = 0; foreach ($issue_vocabularies as $vid => $vocab) { $view_key = 'tid'; if ($i) { $view_key .= "_$i"; } $i++; $identifier = project_issue_views_filter_identifier($vocab->name); $filters[$view_key] = array( 'operator' => 'or', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 1, 'operator' => $identifier . '_op', 'identifier' => $identifier, 'label' => check_plain($vocab->name), 'optional' => 1, 'single' => 1, 'remember' => 0, ), 'type' => 'textfield', 'vid' => $vid, 'id' => 'tid', 'table' => 'term_node', 'field' => 'tid', 'hierarchy' => 0, 'relationship' => 'none', 'reduce_duplicates' => 1, ); } }