First push, taken from the previous Spintrum software model

This commit is contained in:
Samer Afach 2017-01-10 11:14:51 +01:00
commit 7852c4d1d9
36 changed files with 168893 additions and 0 deletions

14
.idea/Spintrum.iml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
</content>
<orderEntry type="jdk" jdkName="Python 3.4.2 (/usr/bin/python3.4)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="projectConfiguration" value="Nosetests" />
<option name="PROJECT_TEST_RUNNER" value="Nosetests" />
</component>
</module>

View File

@ -0,0 +1,10 @@
<component name="ProjectDictionaryState">
<dictionary name="samer">
<words>
<w>afach</w>
<w>libspintrum</w>
<w>samer</w>
<w>spintrum</w>
</words>
</dictionary>
</component>

View File

@ -0,0 +1,10 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="SpellCheckingInspection" enabled="true" level="TYPO" enabled_by_default="true">
<option name="processCode" value="false" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,7 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" />
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

23
.idea/misc.xml Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectInspectionProfilesVisibleTreeState">
<entry key="Project Default">
<profile-state>
<expanded-state>
<State>
<id />
</State>
<State>
<id>Spelling</id>
</State>
</expanded-state>
<selected-state>
<State>
<id>SpellCheckingInspection</id>
</State>
</selected-state>
</profile-state>
</entry>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.4.2 (/usr/bin/python3.4)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Spintrum.iml" filepath="$PROJECT_DIR$/.idea/Spintrum.iml" />
</modules>
</component>
</project>

931
.idea/workspace.xml Normal file
View File

@ -0,0 +1,931 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="f2fcf5e2-7357-47b1-93d2-09e73904866e" name="Default" comment="" />
<ignored path="Spintrum.iws" />
<ignored path=".idea/workspace.xml" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<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="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
<component name="FavoritesManager">
<favorites_list name="Spintrum" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="spintrum.py" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/spintrum/spintrum.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="520">
<caret line="30" column="49" selection-start-line="30" selection-start-column="49" selection-end-line="30" selection-end-column="49" />
<folding>
<element signature="e#0#10#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="formamide.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/formamide.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="formicacid_fit.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/formicacid_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="benzene_fit.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/benzene_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="624">
<caret line="12" column="0" selection-start-line="12" selection-start-column="0" selection-end-line="12" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="benzene.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/benzene.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="624">
<caret line="48" column="17" selection-start-line="48" selection-start-column="17" selection-end-line="48" selection-end-column="17" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="ethanol_fit.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/ethanol_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="methylformate.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/methylformate.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="methylformate_fit.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/methylformate_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="toluene.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/examples/ZULF/toluene.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="meta.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/spintrum/meta.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="52">
<caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Python Script" />
</list>
</option>
</component>
<component name="FindInProjectRecents">
<findStrings>
<find>filterSpectrum</find>
<find>1000</find>
<find>generate_spectrum</find>
<find>_get_derivative</find>
<find>get_correlation_matrix</find>
<find>mp.</find>
<find>optimize</find>
</findStrings>
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/Spintrum.py" />
<option value="$PROJECT_DIR$/__init__.py" />
<option value="$PROJECT_DIR$/Spintrum/setup.py" />
<option value="$PROJECT_DIR$/spintrum/__init__.py" />
<option value="$PROJECT_DIR$/examples/fit.py" />
<option value="$PROJECT_DIR$/examples/MR.py" />
<option value="$PROJECT_DIR$/examples/spectrum.py" />
<option value="$PROJECT_DIR$/setup.py" />
<option value="$PROJECT_DIR$/examples/ZULF/spectrum.py" />
<option value="$PROJECT_DIR$/Makefile" />
<option value="$PROJECT_DIR$/spintrum/meta.py" />
<option value="$PROJECT_DIR$/README.md" />
<option value="$PROJECT_DIR$/examples/ZULF/formicacid_fit .py" />
<option value="$PROJECT_DIR$/spintrum/spintrum.py" />
<option value="$PROJECT_DIR$/examples/TimeDependent/MagneticResonance.py" />
<option value="$PROJECT_DIR$/examples/ZULF/propylenecarbonate.py" />
<option value="$PROJECT_DIR$/examples/ZULF/formamide.py" />
<option value="$PROJECT_DIR$/examples/ZULF/methylformate.py" />
<option value="$PROJECT_DIR$/examples/ZULF/toluene.py" />
<option value="$PROJECT_DIR$/examples/ZULF/acetonitrile.py" />
<option value="$PROJECT_DIR$/examples/ZULF/benzene_fit.py" />
<option value="$PROJECT_DIR$/examples/ZULF/ethanol_fit.py" />
<option value="$PROJECT_DIR$/examples/ZULF/formicacid_fit.py" />
<option value="$PROJECT_DIR$/examples/ZULF/methylformate_fit.py" />
<option value="$PROJECT_DIR$/examples/ZULF/benzene.py" />
</list>
</option>
</component>
<component name="ProjectFrameBounds">
<option name="x" value="-4" />
<option name="y" value="-4" />
<option name="width" value="3204" />
<option name="height" value="1565" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<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" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectView">
<navigator currentView="Scope" currentSubView="Project Files" proportions="" version="1">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
<manualOrder />
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scope">
<subPane subId="Project Files">
<PATH>
<PATH_ELEMENT USER_OBJECT="Root">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="Spintrum">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT USER_OBJECT="Root">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="Spintrum">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="spintrum">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT USER_OBJECT="Root">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="Spintrum">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="examples">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="ZULF">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT USER_OBJECT="Root">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="Spintrum">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
<PATH_ELEMENT USER_OBJECT="examples">
<option name="myItemId" value="" />
<option name="myItemType" value="" />
</PATH_ELEMENT>
</PATH>
</subPane>
</pane>
<pane id="ProjectPane" />
<pane id="Scratches" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/examples/ZULF/toluene.py" />
</component>
<component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$" />
</key>
<key name="CopyFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/examples" />
</key>
</component>
<component name="RunManager" selected="Python.Spectrum-benzene">
<configuration default="true" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="true" type="Tox" factoryName="Tox">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Attests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Doctests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Nosetests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<option name="PARAMS" value="" />
<option name="USE_PARAM" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Unittests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<option name="PUREUNITTEST" value="true" />
<option name="PARAMS" value="" />
<option name="USE_PARAM" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="py.test">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<option name="testToRun" value="" />
<option name="keywords" value="" />
<option name="params" value="" />
<option name="USE_PARAM" value="false" />
<option name="USE_KEYWORD" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-benzene" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/benzene.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-acetonitrile" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/acetonitrile.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-ethanol" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/ethanol.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-formamide" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/formamide.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-methylformate" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/methylformate.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-propylenecarbonate" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/propylenecarbonate.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Spectrum-toluene" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/toluene.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="MR" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/TimeDependent" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/TimeDependent/MagneticResonance.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="false" name="Fit" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/bin/python3.4" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/examples/ZULF" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Spintrum" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/examples/ZULF/methylformate_fit.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<list size="9">
<item index="0" class="java.lang.String" itemvalue="Python.Spectrum-benzene" />
<item index="1" class="java.lang.String" itemvalue="Python.Spectrum-acetonitrile" />
<item index="2" class="java.lang.String" itemvalue="Python.Spectrum-ethanol" />
<item index="3" class="java.lang.String" itemvalue="Python.Spectrum-formamide" />
<item index="4" class="java.lang.String" itemvalue="Python.Spectrum-methylformate" />
<item index="5" class="java.lang.String" itemvalue="Python.Spectrum-propylenecarbonate" />
<item index="6" class="java.lang.String" itemvalue="Python.Spectrum-toluene" />
<item index="7" class="java.lang.String" itemvalue="Python.MR" />
<item index="8" class="java.lang.String" itemvalue="Python.Fit" />
</list>
</component>
<component name="ShelveChangesManager" show_recycled="false">
<option name="remove_strategy" value="false" />
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="f2fcf5e2-7357-47b1-93d2-09e73904866e" name="Default" comment="" />
<created>1471349464312</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1471349464312</updated>
</task>
<servers />
</component>
<component name="TodoView">
<todo-panel id="selected-file">
<is-autoscroll-to-source value="true" />
</todo-panel>
<todo-panel id="all">
<are-packages-shown value="true" />
<is-autoscroll-to-source value="true" />
</todo-panel>
</component>
<component name="ToolWindowManager">
<frame x="-4" y="-4" width="3204" height="1565" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.17803505" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3299279" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.19756098" sideWeight="0.52348644" order="7" side_tool="true" content_ui="tabs" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32899493" sideWeight="0.5" order="1" 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" show_stripe_button="false" weight="0.33" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" />
<window_info id="Python Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.18655097" sideWeight="0.47651356" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="10" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.49791232" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
</layout>
</component>
<component name="Vcs.Log.UiProperties">
<option name="RECENTLY_FILTERED_USER_GROUPS">
<collection />
</option>
<option name="RECENTLY_FILTERED_BRANCH_GROUPS">
<collection />
</option>
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="VcsManagerConfiguration">
<ignored-roots>
<path value="$PROJECT_DIR$/.." />
</ignored-roots>
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<option name="time" value="6" />
</breakpoint-manager>
<watches-manager>
<configuration name="PythonConfigurationType">
<watch expression="names" />
<watch expression="self._all_projection_types" />
</configuration>
</watches-manager>
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/spintrum/__init__.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/spintrum/meta.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/fit.py" />
<entry file="file://$PROJECT_DIR$/Spintrum.py" />
<entry file="file://$PROJECT_DIR$/examples/MR.py" />
<entry file="file://$PROJECT_DIR$/examples/spectrum.py" />
<entry file="file://$PROJECT_DIR$/examples/fit.py" />
<entry file="file://$PROJECT_DIR$/Spintrum.py" />
<entry file="file://$PROJECT_DIR$/examples/fit.py" />
<entry file="file://$PROJECT_DIR$/examples/spectrum.py" />
<entry file="file://$PROJECT_DIR$/examples/MR.py" />
<entry file="file://$PROJECT_DIR$/Spintrum.py" />
<entry file="file://$PROJECT_DIR$/examples/spectrum.py" />
<entry file="file://$PROJECT_DIR$/examples/fit.py" />
<entry file="file://$PROJECT_DIR$/Spintrum.py" />
<entry file="file://$PROJECT_DIR$/examples/fit.py" />
<entry file="file://$USER_HOME$/.PyCharm2016.1/system/python_stubs/-1247971765/builtins.py" />
<entry file="file:///usr/lib/python3/dist-packages/matplotlib/figure.py" />
<entry file="file://$APPLICATION_HOME_DIR$/helpers/pydev/pydev_ipython/matplotlibtools.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="245">
<caret line="143" column="0" selection-start-line="143" selection-start-column="0" selection-end-line="143" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file:///usr/lib/python3/dist-packages/matplotlib/projections/__init__.py" />
<entry file="file://$PROJECT_DIR$/Spintrum.py" />
<entry file="file://$PROJECT_DIR$/__init__.py" />
<entry file="file://$PROJECT_DIR$/spintrum/spintrumpy.py" />
<entry file="file://$PROJECT_DIR$/examples/MR.py" />
<entry file="file://$PROJECT_DIR$/spintrum/__init__.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="312">
<caret line="6" column="0" selection-start-line="6" selection-start-column="0" selection-end-line="6" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/fit.py" />
<entry file="file://$PROJECT_DIR$/examples/spectrum.py" />
<entry file="file://$PROJECT_DIR$/examples/ZULF/spectrum.py" />
<entry file="file://$PROJECT_DIR$/run_build" />
<entry file="file://$PROJECT_DIR$/Makefile">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/CMakeLists.txt">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="290">
<caret line="10" column="42" selection-start-line="10" selection-start-column="42" selection-end-line="10" selection-end-column="42" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/README.md" />
<entry file="file://$PROJECT_DIR$/run_build.sh" />
<entry file="file://$PROJECT_DIR$/setup.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="52">
<caret line="4" column="0" selection-start-line="4" selection-start-column="0" selection-end-line="4" selection-end-column="0" />
<folding>
<element signature="e#0#43#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/data/benzeneFitResult.txt">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/data/ethanolSignal.txt">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/data/formicacidFitResult.txt">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/data/formamideSignal.txt">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="364">
<caret line="7" column="21" selection-start-line="7" selection-start-column="21" selection-end-line="7" selection-end-column="21" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/TimeDependent/MagneticResonance.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/acetonitrile.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/spintrum/meta.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="52">
<caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/benzene_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="624">
<caret line="12" column="0" selection-start-line="12" selection-start-column="0" selection-end-line="12" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/ethanol_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/formicacid_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/methylformate.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/methylformate_fit.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="104">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/toluene.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/propylenecarbonate.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="572">
<caret line="11" column="11" selection-start-line="11" selection-start-column="11" selection-end-line="11" selection-end-column="11" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/benzene.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="624">
<caret line="48" column="17" selection-start-line="48" selection-start-column="17" selection-end-line="48" selection-end-column="17" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/ZULF/formamide.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="e#20#35#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/spintrum/spintrum.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="520">
<caret line="30" column="49" selection-start-line="30" selection-start-column="49" selection-end-line="30" selection-end-column="49" />
<folding>
<element signature="e#0#10#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</component>
<component name="masterDetails">
<states>
<state key="ScopeChooserConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>

123
CMakeLists.txt Normal file
View File

@ -0,0 +1,123 @@
cmake_minimum_required(VERSION 3.0)
PROJECT(Spintrum)
if(NOT DEFINED SpintrumPath)
set(SpintrumPath ../)
endif()
if(NOT DEFINED PolymathPath)
set(PolymathPath ../Polymath/)
endif()
if(NOT DEFINED OpenBLASPath)
set(OpenBLASPath ../OpenBLAS_install/)
endif()
set(CMAKE_BUILD_TYPE Release)
#add_definitions(-DPOLYMATH_DEBUG)
set(VERSION 0.1.5)
add_definitions(-DSPINTRUM_VERSION="${VERSION}")
INCLUDE_DIRECTORIES(${PolymathPath}/include)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${SpintrumPath})
INCLUDE_DIRECTORIES(${OpenBLASPath})
file(GLOB_RECURSE PolymathSrc
"${PolymathPath}/src/*.cpp"
)
file(GLOB_RECURSE includesList
"${PolymathPath}/include/*.h"
"${SpintrumPath}/common/*.h"
)
OPTION(BUILD_SHARED_LIBS "turn OFF for .a libs" ON)
SET(SpintrumMain src/Spintrum.cpp)
ADD_LIBRARY(spintrum SHARED
${SpintrumMain}
${PolymathSrc}
${includesList}
)
if(NOT WIN32)
string(ASCII 27 Esc)
set(ColourReset "${Esc}[m")
set(ColourBold "${Esc}[1m")
set(Red "${Esc}[31m")
set(Green "${Esc}[32m")
set(Yellow "${Esc}[33m")
set(Blue "${Esc}[34m")
set(Magenta "${Esc}[35m")
set(Cyan "${Esc}[36m")
set(White "${Esc}[37m")
set(BoldRed "${Esc}[1;31m")
set(BoldGreen "${Esc}[1;32m")
set(BoldYellow "${Esc}[1;33m")
set(BoldBlue "${Esc}[1;34m")
set(BoldMagenta "${Esc}[1;35m")
set(BoldCyan "${Esc}[1;36m")
set(BoldWhite "${Esc}[1;37m")
endif()
if (UNIX)
IF(CMAKE_BUILD_TYPE MATCHES Release)
message("${Blue}Building in Release mode${ColourReset}")
message("${Red}Be aware that the optimization Ofast is used. If results don't make sense, change that to O3${ColourReset}")
SET( CMAKE_CXX_FLAGS_RELEASE "-Ofast")
SET( CMAKE_C_FLAGS_RELEASE "-Ofast")
ELSE()
message("${BoldRed}Building in Debug mode${ColourReset}")
SET( CMAKE_CXX_FLAGS_RELEASE "-g")
SET( CMAKE_C_FLAGS_RELEASE "-g")
ENDIF(CMAKE_BUILD_TYPE MATCHES Release)
function(FindOpenBLAS path found)
if(EXISTS "${path}/lib/libopenblas.so" OR EXISTS "${path}/lib/libopenblas.so.0")
set(${found} "ON" PARENT_SCOPE)
else()
set(${found} "OFF" PARENT_SCOPE)
endif()
endfunction()
#find OpenBLAS
set(OpenBLASTestPath ${OpenBLASPath})
set(foundOpenBLAS "OFF")
FindOpenBLAS("${OpenBLASTestPath}" "foundOpenBLAS")
if(NOT ${foundOpenBLAS})
set(OpenBLASTestPath "../${OpenBLASTestPath}")
FindOpenBLAS("${OpenBLASTestPath}" "foundOpenBLAS")
endif()
if(${foundOpenBLAS})
message("${BoldGreen}I found a compiled version of OpenBLAS in ${OpenBLASPath}. Everything looks great!${ColourReset}")
TARGET_LINK_LIBRARIES(spintrum -L"${OpenBLASPath}/lib")
TARGET_LINK_LIBRARIES(spintrum -L"../${OpenBLASPath}/lib")
else()
message("${BoldRed}WARNING: OpenBLAS shared library was not found in ${OpenBLASPath}. This leads to a failure in compilation. Consider pulling and compiling OpenBLAS, or alternatively change CMakeLists.txt to fit your configuration.${ColourReset}")
message("${BoldGreen}I will try to fix this problem by considering that your system may have OpenBLAS installed.${ColourReset}")
add_definitions(-DOPENBLAS_FROM_SYSTEM)
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC -shared -pedantic-errors")
file(MAKE_DIRECTORY ${CMAKE_SOURCE_DIR}/spintrum/lib/)
SET(LIBRARY_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/spintrum/lib/) #output libspintrum.so to this directory
TARGET_LINK_LIBRARIES(spintrum libopenblas.so)
TARGET_LINK_LIBRARIES(spintrum)
endif (UNIX)
if (MSVC)
include (GenerateExportHeader)
set(openblasdir D:/libs/OpenBLAS-0.2.19)
set(openblasbuilddir D:/libs/OpenBLAS-0.2.19-build-32/)
add_definitions(-DISWIN32)
TARGET_LINK_LIBRARIES(spintrum -lopenblas)
TARGET_LINK_LIBRARIES(spintrum D:/libs/OpenBLAS-0.2.19-build-32/lib/libopenblas.lib)
TARGET_LINK_LIBRARIES(spintrum)
INCLUDE_DIRECTORIES(include ${openblasdir})
GENERATE_EXPORT_HEADER(m
BASE_NAME m
EXPORT_MACRO_NAME M_EXPORTS
EXPORT_FILE_NAME m_exports.h
STATIC_DEFINE SHARED_EXPORTS_BUILT_AS_STATIC)
endif(MSVC)

16
Makefile Normal file
View File

@ -0,0 +1,16 @@
default:
chmod +x ./run_build.sh
chmod +x ./run_install.sh
./run_build.sh
install:
./run_install.sh
clean:
rm -rf dist
rm -rf build
rm -rf __pycache__
rm -rf spintrum.egg-info
rm -rf spintrum/lib
rm -rf spintrum/*.pyc
rm -rf spintrum/__pycache__

65
README.md Normal file
View File

@ -0,0 +1,65 @@
# Spintrum
A high-performance library for spin simulations, written by Samer Afach
####purpose
Spintrum creates an interface between a high-performance and low-level language (C/C++) and an easy to use and high level language (Python).
##Installation
Spintrum is supported only on Linux/Unix systems, and is primarily tested on Debian. For explanation, look at the FAQ below. If you'd like to compile Spintrum on operating systems other than debian, your efforts to do it will be minimal.
#####Prerequisites
- Linux/Unix (preferably Debian)
- OpenBLAS (read below)
- Polymath (read below)
- cmake
- Python 3.4+
- g++ 4.8+
#####In Python, the following libraries are required
- numpy
- scipy
- mpmath
- matplotlib
#####Do I need to compile OpenBLAS?
This depends on the performance you're trying to achieve. OpenBLAS, when compiled, creates binaries that are processor-specific, in order to achieve the best possible performance. In order to exploit this feature, it's recommended that you compile OpenBLAS.
Don't panic, as you don't have to do this yourself from scratch. The script `get_openblas.sh` should do this for you. It clones the OpenBLAS repository, and changes the optimization level of the compiler settings, and does the compilation. Run it using `sh get_openblas.sh`.
#####What optimization level should I take for OpenBLAS?
The default optimization level for OpenBLAS is `-O2`, which is fair. The script `get_openblas.sh` changes all optimization flags by default to `-Ofast`. This is an extreme exaggeration, and may cause [problems](http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html). I recommend using O2 for tests, and going to Ofast once everything is prepared. Please read [the link](http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) that explains what these optimization flags mean. Then, edit the file `set_openblas_optimization.py`, and change the variable `target_optimization` to the desired optimization level.
#####What if I don't want to compile OpenBLAS?
The compilation script in the directory Spintrum expects a compiled version of OpenBLAS, either in the default directory that the script `get_openblas.sh` downloads and installs to, or an installed version of OpenBLAS in the operating system. Keep in mind that the default OpenBLAS in the Linux operating systems are not generally optimized for your processor.
#####Do I need Polymath?
Definitely! Polymath is a C++ interface to BLAS. It was also written by Spintrum team to separate the Maths library from the programming. Use the script `get_polymath.sh` to clone Polymath.
#####How to install?
In the directory `Spintrum`, there's a `Makefile` that will do everything for you. Simply run the command `make` in that directory, and then if everything runs correctly, and no error messages are issued, run `make install` as root/superuser to install spintrum on your Python installation.
#####How to install missing prerequisites on Debian?
Simply run the following in the terminal (as superuser/root):
```sh
# apt-get install build-essential cmake g++ gcc python3
# pip3 install numpy scipy mpmath matplotlib
```
Note: The `#` means that these commands have to be executed as root. Don't literally type that `#` in the terminal.
#####Testing whether it works
After a successful installation, simply try the examples in the `examples` directory. They should all work, assuming you have
#####Caveat about Jupyter
Spintrum works fine on Jupyter, except that the `stdout` and `stderr` output cannot be seen on Jupyter notebooks for technical reasons. So, if there's a message from the low-level C/C++, it won't be seen. Although unlikely, but in case you have an error and you can't figure out the reason, try running the script in terminal, and see whether the C/C++ interface is reporting an error.
##FAQ
- **Q:** Why is spintrum not supported on Windows?
- **A:** Ignoring that Windows is way slower than Linux for calculations; Spintrum uses the well-known high-performance linear algebra library OpenBLAS. And since Python 3.5+ is compiled on Visual Studio 2015, and since Spintrum uses ctypes, which is the shared-library interface of Python, binary compatibility has to be achieved between Python and the compiled Spintrum library. On the other hand, OpenBLAS does not support compilation on Visual Studio with 64-bit (it supports only 32-bit), meaning that only small spin systems will be properly supported, since memory of 4+ GB cannot be used, which is not worth the effort, as too many changes have to be done to make Spintrum compatible with Windows. In the worst case, use a VMWare Workstation on your Windows Machine, and you'll get the best performance.

View File

@ -0,0 +1,52 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
def run(dirs):
gammas = [10] #Hz/T
jCouplings = [[0]]
BThermal = 10e0
T2 = 10
sampleRate = 1e4
T= 1/sampleRate
B0=10.
B1=0.3e0
points = 1650
f = B0*gammas[0]
bx = np.array([np.sin(2*math.pi*f*t/sampleRate)*B1 for t in range(points)])
by = np.array([np.cos(2*math.pi*f*t/sampleRate)*B1 for t in range(points)])
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': B0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_DEPENDENT,
{'threads': 4, 'samplingRate': sampleRate, 'store': dirs,
'input': {'Bx': bx, 'By': by}})
signal = spintrum.simulate(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinOperations=spinOp)
return signal
#this will result in points in the form xyzxyzxyz (order doesn't make a difference)
data = run('xyz')
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
datanp = np.transpose(np.split(np.array(data),len(data)/3))
ax.plot(datanp[0], datanp[1], datanp[2], label='parametric curve')
ax.legend()
plt.show()

View File

@ -0,0 +1,61 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import time
gammas = [4257.7e4,4257.7e4,4257.7e4,1070.8e4,1070.8e4,-431.6e4]
multips = [2,2,2,2,2,2]
jCouplings = \
[
[0,0,0,136.25,-9.94,-2.03],
[0,0,0,136.25,-9.94,-2.03],
[0,0,0,136.25,-9.94,-2.03],
[0,0,0,0,56.94,2.9],
[0,0,0,0,0,-17.53],
[0,0,0,0,0,0],
]
BThermal = 1.8e0
T2 = 10
sampleRate = 2e3
T= 1/sampleRate
points = 80000
gammah = 2*math.pi*4257.7
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': 4})
start_time = time.time()
signal = spintrum.simulate(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
spinOperations=spinOp)
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
print("Simulation lastet: " + repr(time.time()-start_time) + "s")
plt.plot(signal)
plt.show()
fft = spintrum.FFTSpectralDensity(signal, sampleRate)
plt.plot(fft['x'], fft['y'])
plt.show()

62
examples/ZULF/benzene.py Normal file
View File

@ -0,0 +1,62 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import time
gammas = [4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,1070.8e4]
multips = [2,2,2,2,2,2,2]
jCouplings = \
[
[0,7.54,1.38,0.661,1.38,7.54,158.354],
[0,0,7.543,1.377,0.658,1.373,1.133],
[0,0,0,7.535,1.382,0.658,7.607],
[0,0,0,0,7.535,1.377,-1.296],
[0,0,0,0,0,7.543,7.607],
[0,0,0,0,0,0,1.133],
[0,0,0,0,0,0,0]
]
BThermal = 1.8e0
T2 = 10
sampleRate = 1e3
T= 1/sampleRate
points = 80000
gammah = 2*math.pi*4257.7
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': 4})
start_time = time.time()
signal = spintrum.simulate(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
spinOperations=spinOp)
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
print("Simulation lastet: " + repr(time.time()-start_time) + "s")
plt.plot(signal)
plt.show()
fft = spintrum.FFTSpectralDensity(signal, sampleRate)
plt.plot(fft['x'], fft['y'])
plt.show()

View File

@ -0,0 +1,155 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize
import multiprocessing
import mpmath
mpmath.mp.dps = 25
def filter_spectrum(spec, freq_lim):
x_axis = np.array([])
y_axis = np.array([])
for i in range(len(freq_lim)):
for j in range(len(spec["x"])):
if freq_lim[i][0] <= spec["x"][j] <= freq_lim[i][1]:
x_axis = np.append(x_axis,spec["x"][j])
y_axis = np.append(y_axis,spec["y"][j])
return {"x": x_axis, "y": y_axis}
with open("../data/benzeneSignal.txt") as f:
data = f.readlines()
data = np.array(list(map(np.double,data)))
data = data - np.mean(data)
#defining initial parameters
gammas = [4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,1070.8e4]
multiplicities = [2, 2, 2, 2, 2, 2, 2]
gammah = 2*math.pi*4257.7e4
BThermal = 1.8e0
T2 = 1
points = len(data)
sample_rate = 2000
spectrum_range = [[5, 50], [80, 119], [121, 179], [181, 239], [241, 299]]
jCouplings = \
[
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]
experimental_spectrum = filter_spectrum(spintrum.FFTSpectralDensity(data, sample_rate), spectrum_range)
gen = spintrum.SpinSimulator(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multiplicities,
doPrint=False)
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sample_rate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': multiprocessing.cpu_count()})
gen.update_parameters(spinOperations=spinOp, jCouplings=jCouplings, gyromagneticRatios=gammas)
def generate_spectrum(params):
amplitude = params[13]
T2 = params[14]
jCouplings = \
[
[0, params[0], params[1], params[2],params[1],params[0],params[3]],
[0, 0, params[4], params[5], params[6], params[7], params[8]],
[0, 0, 0, params[9], params[10], params[6], params[11]],
[0, 0, 0, 0, params[9], params[5], params[12]],
[0, 0, 0, 0, 0, params[4], params[11]],
[0, 0, 0, 0, 0, 0, params[8]],
[0, 0, 0, 0, 0, 0, 0],
]
gen.update_parameters(jCouplings=jCouplings)
signal = amplitude*gen.simulate()
signal = signal - np.mean(signal)
signal = [signal[i] * math.exp(-i / sample_rate / T2) for i in range(len(signal))]
fft = filter_spectrum(spintrum.FFTSpectralDensity(signal, sample_rate), spectrum_range)
# plt.plot(fft['x'],fft['y'],realSpectrum['x'],realSpectrum['y'])
# plt.show()
return fft
def objective_func(params):
print(params)
spect = generate_spectrum(params)
func_value = np.sqrt(np.sum((spect['y'] - experimental_spectrum['y']) ** 2))
print('Objective function value:', func_value)
return func_value
pars = np.array([7.54,1.38,0.661,158.354,7.543,1.377,0.658,1.373,1.133,7.535,1.382,7.607,-1.296,0.00002,6])
#pars = np.array([-1.06785235e+00,2.26791767e+02,4.26684847e+00,4.53620118e-05,2.73284204e+00])
# get_objective_func(pars)
optimum_params = scipy.optimize.fmin(objective_func, pars, ftol = 5.0e-13, maxfun = 1)
opt_j_couplings = mpmath.matrix([
[0, optimum_params[0], optimum_params[1], optimum_params[2], optimum_params[1], optimum_params[0], optimum_params[3]],
[0, 0, optimum_params[4], optimum_params[5], optimum_params[6], optimum_params[7], optimum_params[8]],
[0, 0, 0, optimum_params[9], optimum_params[10], optimum_params[6], optimum_params[11]],
[0, 0, 0, 0, optimum_params[9], optimum_params[5], optimum_params[12]],
[0, 0, 0, 0, 0, optimum_params[4], optimum_params[11]],
[0, 0, 0, 0, 0, 0, optimum_params[8]],
[0, 0, 0, 0, 0, 0, 0],
])
CorrelationMatrix = spintrum.get_correlation_matrix(optimum_params, generate_spectrum, objective_func)
print('Correlation matrix: ', '\n', CorrelationMatrix)
print('Parameters at minimum: ','\n', optimum_params)
errorbars = spintrum.get_errorbars(CorrelationMatrix)
print('Standard deviations of parameters: ','\n',errorbars)
#writout to file
np.set_printoptions(suppress=True, precision=20)
fr = open("../data/benzeneFitResult.txt","w")
fr.write('Minimum at J-couplings:\n')
fr.write(str(opt_j_couplings) + '\n')
fr.write('Minimum at paramters:\n')
fr.write(str(optimum_params) + '\n')
fr.write('Parameters standard deviations:\n')
fr.write(str(errorbars)+'\n')
fr.write('Parameters correlation matrix:\n')
fr.write(str(CorrelationMatrix)+'\n')
fr.write('Minimum objective function value: ' + str(objective_func(optimum_params)))
fr.close()
fft_final = generate_spectrum(optimum_params)
plt.plot(fft_final['x'], fft_final['y'], experimental_spectrum['x'], experimental_spectrum['y'])
plt.show()

View File

@ -0,0 +1,155 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize
import multiprocessing
import mpmath as mp
mp.mp.dps = 25
def filter_spectrum(spec, freq_lim):
x_axis = np.array([])
y_axis = np.array([])
for i in range(len(freq_lim)):
for j in range(len(spec["x"])):
if freq_lim[i][0] <= spec["x"][j] <= freq_lim[i][1]:
x_axis = np.append(x_axis,spec["x"][j])
y_axis = np.append(y_axis,spec["y"][j])
return {"x": x_axis, "y": y_axis}
#defining initial parameters
with open("../data/ethanolSignal.txt") as f:
data = f.readlines()
data = np.array(list(map(np.double,data)))
data = data - np.mean(data)
gammas = [4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,1070.8e4]
multips = [2,2,2,2,2,2]
gammah = 2*math.pi*4257.7e4
BThermal = 1.8e0
T2 = 1
points = len(data)
sampleRate = 2000
spectrumRange = [[0,299]]
jCouplings = \
[
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
]
experimental_spectrum = filter_spectrum(spintrum.FFTSpectralDensity(data, 2000), spectrumRange)
gen = spintrum.SpinSimulator(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
doPrint=False)
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': multiprocessing.cpu_count()})
gen.update_parameters(spinOperations=spinOp, jCouplings=jCouplings, gyromagneticRatios=gammas)
def generate_spectrum(params):
amplitude = params[3]
T2 = params[4]
jCouplings = \
[
[0, 0, 0, params[0],params[1],params[1]],
[0, 0, 0, params[0],params[1],params[1]],
[0, 0, 0, params[0],params[1],params[1]],
[0, 0, 0, 0, 0, params[2]],
[0, 0, 0, 0, 0, params[2]],
[0, 0, 0, 0, 0, 0],
]
gen.update_parameters(jCouplings=jCouplings)
signal = amplitude*gen.simulate()
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
fft = filter_spectrum(spintrum.FFTSpectralDensity(signal, 2000), spectrumRange)
# plt.plot(fft['x'],fft['y'],realSpectrum['x'],realSpectrum['y'])
# plt.show()
return fft
def objective_func(params):
print(params)
spect = generate_spectrum(params)
funcValue = np.sqrt(np.sum((spect['y'] - experimental_spectrum['y']) ** 2))
print('Objective function value: ',funcValue)
return funcValue
pars = np.array([7.1,141.0,-4.65,0.00002,6])
#pars = np.array([-1.06785235e+00,2.26791767e+02,4.26684847e+00,l4.53620118e-05,2.73284204e+00])
# get_objective_func(pars)
optimum_params = scipy.optimize.fmin(objective_func, pars, ftol = 5.0e-13, maxfun = 1)
opt_j_couplings = mp.matrix([
[0, 0, 0, optimum_params[0], optimum_params[1], optimum_params[1]],
[0, 0, 0, optimum_params[0], optimum_params[1], optimum_params[1]],
[0, 0, 0, optimum_params[0], optimum_params[1], optimum_params[1]],
[0, 0, 0, 0, 0, optimum_params[2]],
[0, 0, 0, 0, 0, optimum_params[2]],
[0, 0, 0, 0, 0, 0],
])
CorrelationMatrix = spintrum.get_correlation_matrix(optimum_params, generate_spectrum, objective_func)
print('Correlation matrix: ','\n',CorrelationMatrix)
print('Parameters at minimum: ','\n', optimum_params)
errorbars = spintrum.get_errorbars(CorrelationMatrix)
print('Standard deviations of parameters: ','\n',errorbars)
#writout to file
np.set_printoptions(suppress=True,precision=20)
fr = open("../data/ethanolFitResult.txt","w")
fr.write('Minimum at J-couplings:\n')
fr.write(str(opt_j_couplings) + '\n')
fr.write('Minimum at paramters:\n')
fr.write(str(optimum_params) + '\n')
fr.write('Parameters standard deviations:\n')
fr.write(str(errorbars)+'\n')
fr.write('Parameters correlation matrix:\n')
fr.write(str(CorrelationMatrix)+'\n')
fr.write('Minimum objective function value: ' + str(objective_func(optimum_params)))
fr.close()
fft_final = generate_spectrum(optimum_params)
plt.plot(fft_final['x'], fft_final['y'], experimental_spectrum['x'], experimental_spectrum['y'])
plt.show()

View File

@ -0,0 +1,80 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import time
gammas = [-431.6e4,4257.7e4,4257.7e4,4257.7e4]
multips = [2,2,2,2]
jCouplings = \
[
[0,-89.3,-89.3,-13.5],
[0,0,0,8],
[0,0,0,8],
[0,0,0,0],
]
BThermal = 1.8e0
T2 = 5
sampleRate = 2e3
T= 1/sampleRate
points = 80000
specRange = [[0,50],[100,200]]
gammah = 2*math.pi*4257.7e4
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': 4})
def filterSpectrum(spec, freqLim):
xAxis = np.array([])
yAxis = np.array([])
for i in range(len(freqLim)):
for j in range(len(spec["x"])):
if spec["x"][j] >= freqLim[i][0] and spec["x"][j] <= freqLim[i][1]:
xAxis = np.insert(xAxis,-0,spec["x"][j])
yAxis = np.insert(yAxis,-0,spec["y"][j])
return {"x": xAxis, "y": yAxis}
start_time = time.time()
signal = spintrum.simulate(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
spinOperations=spinOp)
print("Simulation lastet: " + repr(time.time()-start_time) + "s")
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
plt.plot(signal)
plt.show()
FFT = spintrum.FFTSpectralDensity(signal, sampleRate)
fft = filterSpectrum(FFT,specRange)
plt.plot(fft['x'], fft['y'])
plt.show()

View File

@ -0,0 +1,142 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize
import multiprocessing
import mpmath as mp
def filter_spectrum(spec, freq_lim):
x_axis = np.array([])
y_axis = np.array([])
for i in range(len(freq_lim)):
for j in range(len(spec["x"])):
if freq_lim[i][0] <= spec["x"][j] <= freq_lim[i][1]:
x_axis = np.append(x_axis,spec["x"][j])
y_axis = np.append(y_axis,spec["y"][j])
return {"x": x_axis, "y": y_axis}
with open("../data/formicacidSignal.txt") as f:
data = f.readlines()
data = np.array(list(map(np.double,data)))
data = data - np.mean(data)
gammas = [4257.7e4,1070.8e4]
multips = [2,2]
gammah = 2*math.pi*4257.7e4
BThermal = 1.8e0
T2 = 1
points = len(data)
sampleRate = 2000
spectrumRange = [[210,230]]
jCouplings = \
[
[0,0],
[0,0],
]
realSpectrum = filter_spectrum(spintrum.FFTSpectralDensity(data, 2000), spectrumRange)
gen = spintrum.SpinSimulator(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
doPrint=False)
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': multiprocessing.cpu_count()})
gen.update_parameters(spinOperations=spinOp, jCouplings=jCouplings, gyromagneticRatios=gammas)
def generate_spectrum(params):
amplitude = params[1]
T2 = params[2]
jCouplings = \
[
[0, params[0]],
[0, 0],
]
gen.update_parameters(jCouplings=jCouplings)
signal = amplitude*gen.simulate()
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
fft = filter_spectrum(spintrum.FFTSpectralDensity(signal, 2000), spectrumRange)
# plt.plot(fft['x'],fft['y'],realSpectrum['x'],realSpectrum['y'])
# plt.show()
return fft
def objective_func(params):
print(params)
spect = generate_spectrum(params)
funcValue = np.sqrt(np.sum((spect['y'] - realSpectrum['y'])**2))
print('Objective function value: ',funcValue)
return funcValue
pars = np.array([222.5,0.000003,6])
#pars = np.array([-1.06785235e+00,2.26791767e+02,4.26684847e+00,4.53620118e-05,2.73284204e+00])
# get_objective_func(pars)
optimum_params = scipy.optimize.fmin(objective_func, pars, ftol = 5.0e-13, maxfun = 1e6)
optjCouplings = mp.matrix([
[0, optimum_params[0]],
[0, 0],
])
CorrelationMatrix = spintrum.get_correlation_matrix(optimum_params, generate_spectrum, objective_func)
print('Correlation matrix: ','\n',CorrelationMatrix)
print('Parameters at minimum: ','\n', optimum_params)
errorbars = spintrum.get_errorbars(CorrelationMatrix)
print('Standard deviations of parameters: ','\n',errorbars)
#writout to file
np.set_printoptions(suppress=True,precision=20)
fr = open("../data/formicacidFitResult.txt","w")
fr.write('Minimum at J-couplings:\n')
fr.write(str(optjCouplings)+'\n')
fr.write('Minimum at paramters:\n')
fr.write(str(optimum_params) + '\n')
fr.write('Parameters standard deviations:\n')
fr.write(str(errorbars)+'\n')
fr.write('Parameters correlation matrix:\n')
fr.write(str(CorrelationMatrix)+'\n')
fr.write('Minimum objective function value: ' + str(objective_func(optimum_params)))
fr.close()
fft_final = generate_spectrum(optimum_params)
plt.plot(fft_final['x'],fft_final['y'],realSpectrum['x'],realSpectrum['y'])
plt.show()

View File

@ -0,0 +1,60 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import time
gammas = [4257.7e4,4257.7e4,4257.7e4,4257.7e4,1070.8e4]
multips = [2,2,2,2,2]
jCouplings = \
[
[0,-0.8,-0.8,-0.8,226.8],
[0,0,0,0,4.0],
[0,0,0,0,4.0],
[0,0,0,0,4.0],
[0,0,0,0,0],
]
BThermal = 1.8e0
T2 = 10
sampleRate = 2e3
T= 1/sampleRate
points = 80000
gammah = 2*math.pi*4257.7
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': 4})
start_time = time.time()
signal = spintrum.simulate(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
spinOperations=spinOp)
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
print("Simulation lastet: " + repr(time.time()-start_time) + "s")
plt.plot(signal)
plt.show()
fft = spintrum.FFTSpectralDensity(signal, sampleRate)
plt.plot(fft['x'], fft['y'])
plt.show()

View File

@ -0,0 +1,156 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize
import multiprocessing
import mpmath as mp
def filter_spectrum(spec, freq_lim):
x_axis = np.array([])
y_axis = np.array([])
for i in range(len(freq_lim)):
for j in range(len(spec["x"])):
if freq_lim[i][0] <= spec["x"][j] <= freq_lim[i][1]:
x_axis = np.append(x_axis,spec["x"][j])
y_axis = np.append(y_axis,spec["y"][j])
return {"x": x_axis, "y": y_axis}
#defining initial parameters
with open("../data/methylformateSignal.txt") as f:
data = f.readlines()
data = np.array(list(map(np.double,data)))
data = data - np.mean(data)
gammas = [4257.7e4,4257.7e4,4257.7e4,4257.7e4,1070.8e4]
multips = [2,2,2,2,2]
gammah = 2*math.pi*4257.7e4
BThermal = 1.8e0
T2 = 1
points = len(data)
sampleRate = 2000
spectrumRange = [[70,119],[121,179],[181,239],[241,299]]
jCouplings = \
[
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
]
experimental_spectrum = filter_spectrum(spintrum.FFTSpectralDensity(data, 2000), spectrumRange)
gen = spintrum.SpinSimulator(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
doPrint=False)
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': multiprocessing.cpu_count()})
gen.update_parameters(spinOperations=spinOp, jCouplings=jCouplings, gyromagneticRatios=gammas)
def generate_spectrum(params):
amplitude = params[3]
T2 = params[4]
jCouplings = \
[
[0, params[0], params[0], params[0],params[1]],
[0, 0, 0, 0, params[2]],
[0, 0, 0, 0, params[2]],
[0, 0, 0, 0, params[2]],
[0, 0, 0, 0, 0],
]
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4 * math.pi / gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': np.float(params[5]), 'By': 0, 'Bz': np.float(params[6])})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': multiprocessing.cpu_count()})
gen.update_parameters(jCouplings=jCouplings, spinOperations=spinOp)
signal = amplitude*gen.simulate()
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
fft = filter_spectrum(spintrum.FFTSpectralDensity(signal, 2000), spectrumRange)
# plt.plot(fft['x'],fft['y'],realSpectrum['x'],realSpectrum['y'])
# plt.show()
return fft
def objective_func(params):
print(params)
spect = generate_spectrum(params)
funcValue = np.sqrt(np.sum((spect['y'] - experimental_spectrum['y']) ** 2))
print('Objective function value: ',funcValue)
return funcValue
pars = np.array([-1.06785235e+00,2.26791767e+02,4.26684847e+00,4.53620118e-05,2.73284204e+00,3.11541220e-09,2.80718054e-09])
#pars = np.array([-1.06785235e+00,2.26791767e+02,4.26684847e+00,4.53620118e-05,2.73284204e+00])
# get_objective_func(pars)
optimum_params = scipy.optimize.fmin(objective_func, pars, ftol = 5.0e-13, maxfun = 1)
optjCouplings = mp.matrix([[0, optimum_params[0], optimum_params[0], optimum_params[0], optimum_params[1]], [0, 0, 0, 0, optimum_params[2]], [0, 0, 0, 0, optimum_params[2]], [0, 0, 0, 0, optimum_params[2]], [0, 0, 0, 0, 0]])
CorrelationMatrix = spintrum.get_correlation_matrix(optimum_params, generate_spectrum, objective_func)
print('Correlation matrix: ','\n',CorrelationMatrix)
print('Parameters at minimum: ','\n', optimum_params)
errorbars = spintrum.get_errorbars(CorrelationMatrix)
print('Standard deviations of parameters: ','\n',errorbars)
#writout to file
np.set_printoptions(suppress=True,precision=20)
fr = open("../data/methylformateFitResult.txt","w")
fr.write('Minimum at J-couplings:\n')
fr.write(str(optjCouplings)+'\n')
fr.write('Minimum at paramters:\n')
fr.write(str(optimum_params) + '\n')
fr.write('Parameters standard deviations:\n')
fr.write(str(errorbars)+'\n')
fr.write('Parameters correlation matrix:\n')
fr.write(str(CorrelationMatrix)+'\n')
fr.write('Minimum objective function value: ' + str(objective_func(optimum_params)))
fr.close()
fft_final = generate_spectrum(optimum_params)
plt.plot(fft_final['x'], fft_final['y'], experimental_spectrum['x'], experimental_spectrum['y'])
plt.show()

64
examples/ZULF/toluene.py Normal file
View File

@ -0,0 +1,64 @@
#!/usr/bin/python3
import spintrum
import math
import matplotlib.pyplot as plt
import numpy as np
import time
gammas = [1070.8e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4,4257.7e4]
multips = [2,2,2,2,2,2,2,2,2]
jCouplings = \
[
[0,125.99,125.99,125.99,4.53,0.63,0.56,0.63,4.53],
[0,0,0,0,-0.69,0.3,-0.52,0.3,-0.69],
[0,0,0,0,-0.69,0.3,-0.52,0.3,-0.69],
[0,0,0,0,-0.69,0.3,-0.52,0.3,-0.69],
[0,0,0,0,0,7.655,1.273,0.61,1.902],
[0,0,0,0,0,0,7.417,1.442,0.61],
[0,0,0,0,0,0,0,7.417,1.273],
[0,0,0,0,0,0,0,0,7.655],
[0,0,0,0,0,0,0,0,0],
]
BThermal = 1.8e0
T2 = 10
sampleRate = 2e3
T= 1/sampleRate
points = 80000
gammah = 2*math.pi*4257.7
spinOp = spintrum.SpinOperations()
spinOp.add_operation(spintrum.SpinOperations.OPERATION__THERMAL_POPULATE,
{'Bx': 0, 'By': 0, 'Bz': BThermal, 'T': 293.778})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__TIP_SPINS,
{'direction': 'y', 'BVsTArea': 4*math.pi/gammah})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__SET_HAMILTONIAN,
{'Bx': 0, 'By': 0, 'Bz': 0})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION,
{'samplingRate': sampleRate, 'measurementDirection': 'z'})
spinOp.add_operation(spintrum.SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT,
{'points': points, 'threads': 4})
start_time = time.time()
signal = spintrum.simulate(gyromagneticRatios=gammas,
jCouplings=jCouplings,
spinMultiplicities=multips,
spinOperations=spinOp)
signal = signal - np.mean(signal)
signal = [signal[i]*math.exp(-i/sampleRate/T2) for i in range(len(signal))]
print("Simulation lastet: " + repr(time.time()-start_time) + "s")
#plt.plot(signal)
#plt.show()
fft = spintrum.FFTSpectralDensity(signal, sampleRate)
#plt.plot(fft['x'], fft['y'])
#plt.show()

View File

@ -0,0 +1,39 @@
Minimum at J-couplings:
[0.0 7.540000000000000035527137 1.37999999999999989341859 0.6940500000000000557776048 1.37999999999999989341859 7.540000000000000035527137 158.3540000000000134150469]
[0.0 0.0 7.543000000000000149213975 1.377000000000000001776357 0.6580000000000000293098879 1.372999999999999998223643 1.133000000000000007105427]
[0.0 0.0 0.0 7.535000000000000142108547 1.381999999999999895194946 0.6580000000000000293098879 7.607000000000000206057393]
[0.0 0.0 0.0 0.0 7.535000000000000142108547 1.377000000000000001776357 -1.296000000000000040856207]
[0.0 0.0 0.0 0.0 0.0 7.543000000000000149213975 7.607000000000000206057393]
[0.0 0.0 0.0 0.0 0.0 0.0 1.133000000000000007105427]
[0.0 0.0 0.0 0.0 0.0 0.0 0.0]
Minimum at paramters:
[ 7.54000000000000003553 1.37999999999999989342
0.69405000000000005578 158.35400000000001341505
7.54300000000000014921 1.37700000000000000178
0.65800000000000002931 1.37299999999999999822
1.13300000000000000711 7.53500000000000014211
1.38199999999999989519 7.60700000000000020606
-1.29600000000000004086 0.00002 6. ]
Parameters standard deviations:
[ 0.01213036128028350744 0.01200338965431838219 0.0210108319218480534
0.00136520954965830372 0.00207036522512347001 0.0015403380168111558
0.002411457870921565 0.00388774145155117157 0.0115697414734789103
0.00197797340829316192 0.00378925067269910397 0.01309609727481571284
0.02228143292531298975 0.00000013041758667639 0.08099564331836582587]
Parameters correlation matrix:
[ 0.0001471456647902013181383402 0.00001463222969485299177267973 -0.00006909596379679264589945903 -0.000009879358894976308872795249 -0.0000009910243900245024325036503 -0.000002509748557468651844392826 -0.000002380514305191314647678003 -0.000001532797369848477294597076 -0.0001398171521420891800876204 0.000001422052124704963073199576 -0.00001037268069958482290642726 -0.00001290226212709788198467148 0.00007096566048036505325667219 -1.702553129336511984544059e-10 0.00004275020004048705398448456]
[ 0.00001463222969485299177267973 0.0001440813631933975880817379 0.00002299492026289425009574231 0.00001037831140663546812973995 0.000004641419189000230273160295 0.0000003481765790202689986629226 0.000005497366076771748661640629 0.000002877276454724989752027814 -0.00001362792654992391090535695 0.0000004161081524168458245327233 -0.000002483428954058797310899994 -0.0001558767501752093491889536 -0.00002141545832708516017103168 -6.012359324553393495710444e-11 -0.00002327038396238911095653417]
[ -0.00006909596379679264589945903 0.00002299492026289425009574231 0.0004414550580481491548513489 0.000001108435560228381067375232 -0.00001975420180487688038510312 0.00001453060280812084487906817 0.00002318209036413609021209115 0.00001039593258646703331312574 0.00006364589864333445436952719 -0.000009398587641029470657017377 0.00002622272826720824973467517 -0.000008764476892287513000476972 -0.000466746002920191158409556 1.248762095118255000331241e-10 0.00001130020472156932208081689]
[ -0.000009879358894976308872795249 0.00001037831140663546812973995 0.000001108435560228381067375232 0.000001863797114478228603607421 0.0000007476440865756702094209745 1.123978176405166973781769e-8 0.0000002553464654493212747923789 0.0000003195064918052377525208331 0.000009443194729269174453253087 7.221575647409583548534879e-8 0.000000349931576923391013309441 -0.00001190107927369451519111038 -0.0000008315685547761382561697822 6.700368978239857808480007e-12 -0.000005586326111486780414234254]
[-0.0000009910243900245024325036503 0.000004641419189000230273160295 -0.00001975420180487688038510312 0.0000007476440865756702094209745 0.000004286412165400555968378269 -0.00000148069638031103530582914 -0.00000173209322151311247953546 -0.0000005677951950371133070047416 0.0000009378771834264744655292185 0.000001247272798757033414925511 -0.000001274930289723080766708529 -0.000006204113311550526544923224 0.00002140476713125757962515133 -2.303859357294487235932149e-11 -0.0000003321116977367169408111833]
[ -0.000002509748557468651844392826 0.0000003481765790202689986629226 0.00001453060280812084487906817 1.123978176405166973781769e-8 -0.00000148069638031103530582914 0.000002372641206033724645831738 0.0000003949086502734464393062185 0.000001888143503238488927826451 0.000002307832893099388443109272 -0.000001330141506298025966824523 0.000001023838420449584372820466 8.810992240617305314994453e-8 -0.00001532057310382572305396533 6.464365426716748781623857e-13 0.000008235154837073978975731815]
[ -0.000002380514305191314647678003 0.000005497366076771748661640629 0.00002318209036413609021209115 0.0000002553464654493212747923789 -0.00000173209322151311247953546 0.0000003949086502734464393062185 0.000005815129063229567994669581 -0.0000008188514962362312139895792 0.000001586158863679219511860753 -0.000001061890629089395632567779 0.0000006323002134620725592762107 -0.000004645446730989817348446203 -0.00002427101958370795139270938 1.038492242263116564566961e-11 -0.000008219887074829020900351506]
[ -0.000001532797369848477294597076 0.000002877276454724989752027814 0.00001039593258646703331312574 0.0000003195064918052377525208331 -0.0000005677951950371133070047416 0.000001888143503238488927826451 -0.0000008188514962362312139895792 0.00001511453359410921012152708 0.000000999587640990087513467813 -0.000001931320208821247224439329 0.0000055775471016662317599875 -0.000003803551035702625255040296 -0.00001044948729450380108855006 1.538488794122819589494189e-11 -0.00000190273597974101894946311]
[ -0.0001398171521420891800876204 -0.00001362792654992391090535695 0.00006364589864333445436952719 0.000009443194729269174453253088 0.0000009378771834264744655292185 0.000002307832893099388443109272 0.000001586158863679219511860753 0.0000009995876409900875134678131 0.0001338589177631379405020443 -0.000001347004704046966658459637 0.000009310637780617520017116411 0.00001131355875911897408321388 -0.00006530765877458676341747736 1.506546328775637756433659e-10 -0.0000301979608076350653658923]
[ 0.000001422052124704963073199576 0.0000004161081524168458245327232 -0.000009398587641029470657017377 7.221575647409583548534879e-8 0.000001247272798757033414925511 -0.000001330141506298025966824523 -0.000001061890629089395632567779 -0.000001931320208821247224439329 -0.000001347004704046966658459637 0.00000391237880391486694459757 -0.0000006379463858305498051696242 -0.0000002334284653952341494558095 0.000008643432009244179075330804 1.758741509731881657071911e-12 -0.00000487121626283840634144112]
[ -0.00001037268069958482290642726 -0.000002483428954058797310899994 0.00002622272826720824973467517 0.000000349931576923391013309441 -0.000001274930289723080766708529 0.000001023838420449584372820466 0.0000006323002134620725592762107 0.0000055775471016662317599875 0.000009310637780617520017116411 -0.0000006379463858305498051696242 0.00001435842066055061071562628 0.000003028275428748878192197676 -0.00002776991450362346709938132 2.814838265884042881741137e-11 -0.00001169416998368706644677807]
[ -0.00001290226212709788198467148 -0.0001558767501752093491889536 -0.000008764476892287513000476973 -0.00001190107927369451519111038 -0.000006204113311550526544923224 8.810992240617305314994455e-8 -0.000004645446730989817348446203 -0.000003803551035702625255040296 0.00001131355875911897408321388 -0.0000002334284653952341494558095 0.000003028275428748878192197676 0.0001715077638314355195700391 0.000005116547306256408779515563 7.767623556078226544272074e-11 0.000019275139606341545706687]
[ 0.00007096566048036505325667219 -0.00002141545832708516017103168 -0.000466746002920191158409556 -0.0000008315685547761382561697822 0.00002140476713125757962515133 -0.00001532057310382572305396532 -0.00002427101958370795139270938 -0.00001044948729450380108855006 -0.00006530765877458676341747736 0.000008643432009244179075330805 -0.00002776991450362346709938132 0.000005116547306256408779515563 0.0004964622532052218464903146 -1.304877543835054883828051e-10 -0.00001404076566819395902521567]
[ -1.702553129336511984544059e-10 -6.012359324553393495710443e-11 1.248762095118255000331241e-10 6.700368978239857808480007e-12 -2.303859357294487235932149e-11 6.464365426716748781623857e-13 1.038492242263116564566961e-11 1.538488794122819589494189e-11 1.506546328775637756433659e-10 1.758741509731881657071911e-12 2.814838265884042881741137e-11 7.767623556078226544272074e-11 -1.304877543835054883828051e-10 1.700874691449460977731785e-14 -7.720781640183639711727769e-9]
[ 0.00004275020004048705398448456 -0.00002327038396238911095653417 0.00001130020472156932208081689 -0.000005586326111486780414234254 -0.0000003321116977367169408111833 0.000008235154837073978975731815 -0.000008219887074829020900351506 -0.00000190273597974101894946311 -0.0000301979608076350653658923 -0.00000487121626283840634144112 -0.00001169416998368706644677807 0.00001927513960634154570668701 -0.00001404076566819395902521567 -7.720781640183639711727769e-9 0.006560294236555937715697575]
Minimum objective function value: 0.00103043119564

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
Minimum at J-couplings:
[0.0 0.0 0.0 7.099999999999999644728632 141.0 141.0]
[0.0 0.0 0.0 7.099999999999999644728632 141.0 141.0]
[0.0 0.0 0.0 7.099999999999999644728632 141.0 141.0]
[0.0 0.0 0.0 0.0 0.0 -4.882500000000000284217094]
[0.0 0.0 0.0 0.0 0.0 -4.882500000000000284217094]
[0.0 0.0 0.0 0.0 0.0 0.0]
Minimum at paramters:
[ 7.09999999999999964473 141. -4.88250000000000028422
0.00002 6. ]
Parameters standard deviations:
[ 0.03322511176186732779 0.00875703636437601129 0.00859062850557597291
0.00000523277859604197 3.77791757313063492063]
Parameters correlation matrix:
[ 0.001103908051588574804254193 -0.0001006480358644767479148856 0.00005611320233879484823628018 -2.237414104467287731378798e-11 0.0002700305105131311016724805]
[-0.0001006480358644767479148856 0.00007668568588700384258089065 -0.00004179674357134708614132537 -5.925975514198601921081523e-9 0.004471293184115583646988029]
[0.00005611320233879484823628018 -0.00004179674357134708614132537 0.00007379889812081447682909023 1.350386848067927730816378e-8 -0.0102277945204446472126845]
[-2.237414104467287731378797e-11 -5.925975514198601921081523e-9 1.350386848067927730816378e-8 2.738197183519495203009604e-11 -0.00001880755267537564555294751]
[ 0.0002700305105131311016724805 0.004471293184115583646988029 -0.0102277945204446472126845 -0.00001880755267537564555294751 14.27266118936926548689719]
Minimum objective function value: 0.0125706965818

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
Minimum at J-couplings:
[0.0 222.1877481194236167993949493393302]
[0.0 0.0]
Minimum at paramters:
[ 222.18774811942361679939 0.00000700376782247602
1.69818437855777837342]
Parameters standard deviations:
[ 0.00777056220300333632 0.00000037317354042493 0.15122981127762022413]
Parameters correlation matrix:
[ 0.000060381636950744068972239730989777295 0.00000000071197799223094697619657741707518772 -0.00034401826493826866573828698109969613]
[0.00000000071197799223094697619657741707518772 1.3925849127327319427483753807104422e-13 -0.000000047394629923508054151430233544667943]
[ -0.00034401826493826866573828698109969613 -0.000000047394629923508054151430233544667943 0.02287045581906462914171822272631652]
Minimum objective function value: 0.000654933531164

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,23 @@
Minimum at J-couplings:
[0.0 -1.0678523499999998946918822184670717 -1.0678523499999998946918822184670717 -1.0678523499999998946918822184670717 226.79176699999999300416675396263599]
[0.0 0.0 0.0 0.0 4.266848470000000226320935325929895]
[0.0 0.0 0.0 0.0 4.266848470000000226320935325929895]
[0.0 0.0 0.0 0.0 4.266848470000000226320935325929895]
[0.0 0.0 0.0 0.0 0.0]
Minimum at paramters:
[ -1.06785234999999989469 226.79176699999999300417
4.26684847000000022632 0.0000453620118 2.73284203999999997237
0.0000000031154122 0.00000000280718054 ]
Parameters standard deviations:
[ 0.02242942966348998243 0.00190541137555014835 0.02303976419604812642
0.00000028974733647283 0.07572279537417966888 0.00000000003027146215
0.00000000004010792718]
Parameters correlation matrix:
[ 0.00050307931502944447178626360068638525 0.000029995480328595218968415826471918807 -0.00051359745782623199683628427562180084 0.000000000251280842447412138296006599769143 -0.00025439816330555875699204056496202219 1.9773403201808349316594111150447776e-14 7.0782623258978496584017170158219388e-15]
[ 0.000029995480328595218968415826471918807 0.0000036305925100759085887128102540087185 -0.000031545306263632570913346524380184319 -2.8590806792482291405525580037517663e-11 0.00000099665502856831515009376374925722041 5.2053844502032590732856596844496641e-15 5.6557052486419077136597636259362455e-16]
[ -0.00051359745782623199683628427562180084 -0.000031545306263632570913346524380184319 0.00053083073420950117280621071233900746 -0.00000000023963740826851480843983608530501171 0.00025228083948647103053486958411894584 -2.6259436597096508763502191603902104e-14 -5.617433835087409035349599078746469e-15]
[0.000000000251280842447412138296006599769143 -2.8590806792482291405525580037517663e-11 -0.00000000023963740826851480843983608530501171 8.3953518993101093428195753947557931e-14 -0.000000016426706608716963060350415785300258 -1.2389127603544075455328883147971448e-19 3.4049961328862909668053015097419539e-18]
[ -0.00025439816330555875699204056496202219 0.00000099665502856831515009376374925722041 0.00025228083948647103053486958411894584 -0.000000016426706608716963060350415785300258 0.0057339417392798879484838245926050435 8.3848437595250813682163955020503337e-13 -1.7808587170356099750124293395687296e-13]
[ 1.9773403201808349316594111150447776e-14 5.2053844502032590732856596844496641e-15 -2.6259436597096508763502191603902104e-14 -1.2389127603544075455328883147971448e-19 8.3848437595250813682163955020503337e-13 9.1636142048929983066902979806790567e-22 6.2746417676452346808851531983373244e-22]
[ 7.0782623258978496584017170158219388e-15 5.6557052486419077136597636259362455e-16 -5.617433835087409035349599078746469e-15 3.4049961328862909668053015097419539e-18 -1.7808587170356099750124293395687296e-13 6.2746417676452346808851531983373244e-22 1.608645822742293354407757298544296e-21]
Minimum objective function value: 0.00132379434362

File diff suppressed because it is too large Load Diff

32
run_build.sh Normal file
View File

@ -0,0 +1,32 @@
#!/bin/bash
#go to the directory of the script
reldir=`dirname $0`
cd $reldir
directory=`pwd`
rm -rf dist
rm -rf build
rm -rf spintrum.egg-info/
mkdir build
cd build
cmake -DOpenBLASPath=../OpenBLAS_install/ ..
if [ $? -ne 0 ]; then
echo 'CMake failed to run. Are you sure that CMake is installed?'
exit
fi
make
if [ $? -ne 0 ]; then
echo 'make failed to run.'
exit
fi
cd ..
python3 setup.py --verbose sdist
if [ $? -ne 0 ]; then
echo 'Python package creator installation script failed.'
exit
fi

20
run_install.sh Normal file
View File

@ -0,0 +1,20 @@
#!/bin/bash
#go to the directory of the script
reldir=`dirname $0`
cd $reldir
directory=`pwd`
RED='\033[1;31m'
NC='\033[0m' # No Color
if [ "$(id -u)" != "0" ]; then
echo -e "${RED}ERROR: This script must be run as root${NC}" 1>&2
exit 1
fi
pip3 install dist/spintrum* --upgrade
if [ $? -ne 0 ]; then
echo 'Package installation failed. Did you build the package? Do you have pip3 installed?'
exit
fi

28
setup.py Normal file
View File

@ -0,0 +1,28 @@
from setuptools import setup, find_packages
from spintrum import meta
import os
import sys
del os.link #solve hardlinking problem when using NTFS drive
def _print_error(msg):
sys.stderr.write("\n\nERROR: " + msg + "\n\n\n")
dirname = "spintrum"
lib_file = "lib/libspintrum.so"
if not os.path.isfile(os.path.join(dirname,lib_file)):
_print_error("Unable to find the compiled library header. Please compile Spintrum before installing it.")
os._exit(1)
setup(name='spintrum',
version=meta.__version__,
description='Software for spin systems simulation',
url='http://www.afach.de',
author='Samer Afach',
author_email='samer@afach.de',
license='MPL',
packages=['spintrum'],
package_data={'': ['lib/libspintrum.so']},
zip_safe=False
)

8
spintrum/__init__.py Normal file
View File

@ -0,0 +1,8 @@
try:
from spintrum import *
from meta import *
except:
from spintrum.spintrum import *
from spintrum.meta import *
__all__ = ['spintrum','meta']

1
spintrum/meta.py Normal file
View File

@ -0,0 +1 @@
__version__ = "0.1.6"

747
spintrum/spintrum.py Normal file
View File

@ -0,0 +1,747 @@
import sys
import traceback
import copy
import ctypes as c
import numpy as np
import os
import mpmath
_SpintrumLibPath = os.path.join(os.path.dirname(os.path.abspath(__file__)),"lib/libspintrum.so")
mpmath.mp.dps = 50
def fft_spectral_density(data_list, sampling_rate):
"""
Calculates the amplitude spectral density with both x and y axes
:param data_list: Data, for which the FFT to be taken
:param sampling_rate: the sample rate of the data
:return: a dict with two elements, "x" for the x-axis (frequency axis),
and "y" for the y-axis (the amplitude axis with units Amplitude/sqrt(Hz))
"""
N = len(data_list)
fft_data = np.fft.rfft(data_list)[0:int(N / 2 + 1)]
bandwidth = np.double(sampling_rate / 2)
scaling_factor = np.sqrt(1/bandwidth/np.double(N))
x_axis = sampling_rate * np.array(range(int(N / 2 + 1))) / (np.double(N))
abs_fft_data = scaling_factor*np.array(list(map(np.absolute,fft_data)))
return {"x": x_axis, "y": abs_fft_data}
def FFTSpectralDensity(data_list, sampling_rate):
"""
Deprecated. Please use fft_spectral_density()
"""
return fft_spectral_density(data_list, sampling_rate)
def who_am_i():
stack = traceback.extract_stack()
filename, code_line, func_name, text = stack[-2]
return func_name
def _print_error(msg_str):
sys.stderr.write(msg_str + "\n")
if not os.path.exists(_SpintrumLibPath):
msg = "WARNING: Could not load the spintrum shared library in path " \
+ _SpintrumLibPath + ". This means that the installation is not valid " \
"and will most likely not work."
_print_error(msg)
print(msg)
def _raise_error(msg_str):
sys.stderr.write(msg_str + "\n")
raise Exception(msg_str)
def _is_var_type_correct(value, type_or_types):
if type(type_or_types) is list:
for tp in type_or_types:
if type(value) is tp:
return True
return False
else:
if type(value) is type_or_types:
return True
else:
return False
def _get_types_list_types_names(type_or_types):
if type(type_or_types) is list:
return str([tp.__name__ for tp in type_or_types])
else:
return str(type_or_types.__name__)
def _check_dict_elements_types(input_dict, types_dict):
for val in input_dict:
if val in types_dict:
if _is_var_type_correct(input_dict[val], types_dict[val]) is False:
_raise_error("Error: Type is not of expected type for variable: " + str(val) +
". Possible allowed type(s) are: " + _get_types_list_types_names(types_dict[val]))
def _check_elements_exist_in_dict(input_dict, must_exist, can_exist):
for el in must_exist:
if el not in input_dict:
_raise_error("Error: You should specify a value for: " + el)
joined_elements = must_exist + can_exist
for el in input_dict:
if el not in joined_elements:
_raise_error("Error: You have specified an unknown variable: " + el)
def _analyze_direction_string(dirs):
activated_directions = {'x': 0, 'y': 0, 'z': 0, 'dirs': dirs}
if (len(dirs) != 0) and ("x" not in dirs) and ("y" not in dirs) and ("z" not in dirs):
_raise_error("Directions, for which trace has to be stored must be given as a string; eg x or xyz or xz, etc.")
else:
for c in dirs:
if c == 'x':
activated_directions['x'] = 1
elif c == 'y':
activated_directions['y'] = 1
elif c == 'z':
activated_directions['z'] = 1
return activated_directions
class SpinOperations:
_OPERATION_NAME_IDENTIFIER = '_OperationIdentifier'
OPERATION__THERMAL_POPULATE = 0
OPERATION__TIP_SPINS = 1
OPERATION__SET_HAMILTONIAN = 2
OPERATION__EVOLVE_TIME_INDEPENDENT = 3
OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION = 4
OPERATION__EVOLVE_TIME_DEPENDENT = 5
def __init__(self):
self.operations_stack = None
self.total_num_of_points = 0
self.clear_operations()
def clear_operations(self):
self.operations_stack = []
def add_operation(self, operation, parameters={}):
if type(parameters) is not dict:
_raise_error(who_am_i() + ": Error: parameters should be a dict.")
if operation == SpinOperations.OPERATION__THERMAL_POPULATE:
argument_types = {'Bx': [int, float], 'By': [int, float], 'Bz': [int, float],'T': [int,float]}
must_exist_arguments = ['Bx', 'By', 'Bz','T']
optional_arguments = []
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
params_copy = copy.deepcopy(parameters)
params_copy.update({SpinOperations._OPERATION_NAME_IDENTIFIER: operation})
self.operations_stack.append(params_copy)
elif operation == SpinOperations.OPERATION__TIP_SPINS:
argument_types = {'direction': str, 'BVsTArea': [int, float]}
must_exist_arguments = ['direction', 'BVsTArea']
optional_arguments = []
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
params_copy = copy.deepcopy(parameters)
params_copy.update({SpinOperations._OPERATION_NAME_IDENTIFIER: operation})
self.operations_stack.append(params_copy)
elif operation == SpinOperations.OPERATION__SET_HAMILTONIAN:
argument_types = {'Bx': [int, float], 'By': [int, float],
'Bz': [int, float], 'samplingRate': [int, float]}
must_exist_arguments = []
optional_arguments = ['Bx', 'By', 'Bz']
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
params_copy = copy.deepcopy(parameters)
params_copy.update({SpinOperations._OPERATION_NAME_IDENTIFIER: operation})
self.operations_stack.append(params_copy)
elif operation == SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT:
argument_types = {'points': int, 'threads': int}
must_exist_arguments = ['points', 'threads']
optional_arguments = []
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
params_copy = copy.deepcopy(parameters)
params_copy.update({SpinOperations._OPERATION_NAME_IDENTIFIER: operation})
self.total_num_of_points += parameters['points']
self.operations_stack.append(params_copy)
elif operation == SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION:
argument_types = {'samplingRate': [int, float], 'measurementDirection': str}
must_exist_arguments = ['samplingRate', 'measurementDirection']
optional_arguments = []
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
params_copy = copy.deepcopy(parameters)
params_copy.update({SpinOperations._OPERATION_NAME_IDENTIFIER: operation})
self.operations_stack.append(params_copy)
elif operation == SpinOperations.OPERATION__EVOLVE_TIME_DEPENDENT:
argument_types = {'threads': int, 'input': dict, 'samplingRate': [int, float], 'store': str}
must_exist_arguments = ['threads', 'input', 'samplingRate', ]
optional_arguments = ['store']
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
# use set to remove duplicates, and restore in dirs_to_store to get the reduced version
# (removing duplicates preserves order by using key=parameters['store'].index)
parameters['dirs_to_store'] = \
_analyze_direction_string(''.join(sorted(set(parameters['store']), key=parameters['store'].index)))
# total number of points = number of input values*number of directions to measure
self.total_num_of_points += \
len(list(parameters['input'].values())[0])*len(parameters['dirs_to_store']['dirs'])
params_copy = copy.deepcopy(parameters)
params_copy.update({SpinOperations._OPERATION_NAME_IDENTIFIER: operation})
self.operations_stack.append(params_copy)
else:
_raise_error("Error: Operation Unknown!")
def _check_j_couplings_sanity(j_couplings):
"""
raises an error if j couplings don't make sense
:param j_couplings:
:return:
"""
if j_couplings is None: #no j-couplings provided
return
for i in range(len(j_couplings)):
if len(j_couplings[i]) != len(j_couplings):
_raise_error("Error: j-couplings must be a square matrix.")
for j in range(len(j_couplings[i])):
if j_couplings[i][j] != 0 and i >= j:
_raise_error("Error: j-couplings must be an upper triangular matrix. "
"All other elements must be exactly 0.")
def simulate(**kwargs):
argument_types = {'gyromagneticRatios': list, 'jCouplings': list, 'spinMultiplicities': list,
'spinOperations': SpinOperations}
must_exist_arguments = ['gyromagneticRatios', 'spinOperations']
optional_arguments = ['jCouplings','spinMultiplicities']
_check_elements_exist_in_dict(kwargs, must_exist_arguments, optional_arguments)
_check_dict_elements_types(kwargs, argument_types)
if 'jCouplings' not in kwargs:
kwargs['jCouplings'] = None
if 'spinMultiplicities' not in kwargs:
kwargs['spinMultiplicities'] = None
_check_j_couplings_sanity(kwargs['jCouplings'])
if kwargs['spinMultiplicities'] is not None and \
len(kwargs['gyromagneticRatios']) != len(kwargs['spinMultiplicities']):
_raise_error("Spin multiplicities must have a length equal to the gyromagnetic ratios, "
"or alternatively, if you keep it empty, then it is assumed that all spins are 1/2")
# print(kwargs)
return _get_signal_c_call(kwargs)
class _CSpinOperation(c.Structure):
_fields_ = [("OperationIdentifier", c.c_long),
("Params_int_count", c.c_long),
("Params_int", c.POINTER(c.c_long)),
("Params_real_count", c.c_long),
("Params_real", c.POINTER(c.c_double)),
("Params_array_count", c.c_long),
("Params_array_lengths", c.POINTER(c.c_long)),
("Params_array_names", c.POINTER(c.POINTER(c.c_char))),
("Params_array", c.POINTER(c.POINTER(c.c_double)))
]
def _direction_str_to_int(dir_str):
if dir_str.lower() == 'x':
return 0
elif dir_str.lower() == 'y':
return 1
elif dir_str.lower() == 'z':
return 2
else:
_raise_error("Direction of the tipping magnetic field can be either x, y or z. "
"You've entered \"" + dir_str + "\"")
def _create_c_operation(operation_id, int_params, real_params, array_params):
# if int params exist, make them in a pointer to an array, otherwise, make it NULL (None)
if len(int_params) > 0:
int_params_c = (c.c_long * len(int_params))(*int_params) #convert list to c-array
int_params_ptr = c.cast(int_params_c, c.POINTER(c.c_long)) #cast array to pointer
else:
int_params_ptr = None
#if real params exist, make them in a pointer to an array, otherwise, make it NULL (None)
if len(real_params) > 0:
real_params_c = (c.c_double * len(real_params))(*real_params) #convert list to c-array
real_params_ptr = c.cast(real_params_c, c.POINTER(c.c_double)) #cast array to pointer
else:
real_params_ptr = None
if len(array_params) > 0:
# arrays lengths
array_lengths_list = list(map(len,array_params.values()))
data_array_lengths_c = (c.c_long * len(array_params))(*array_lengths_list) #convert list to c-array
data_array_lengths_ptr = c.cast(data_array_lengths_c, c.POINTER(c.c_long)) #cast array to pointer
# arrays labels
labels_array_type = (c.POINTER(c.c_char)*len(array_params))
labels_c_array = labels_array_type()
labels_keys_list = list(array_params.keys())
for i in range(len(labels_keys_list)):
labels_c_array[i] = c.create_string_buffer(str.encode(labels_keys_list[i]))
# arrays data arrays
arrays_array_type = (c.POINTER(c.c_double) * len(array_params))
arrays_c_array = arrays_array_type()
arrays_list = list(array_params.values())
for i in range(len(arrays_list)):
single_array_c_type = (c.c_double * len(arrays_list[i]))(*arrays_list[i]) # convert list to c-array
single_array_c = single_array_c_type
arrays_c_array[i] = c.cast(single_array_c, c.POINTER(c.c_double)) #cast array to pointer
else:
data_array_lengths_ptr = None
labels_c_array = None
arrays_c_array = None
op_values = _CSpinOperation(operation_id,
len(int_params), int_params_ptr,
len(real_params), real_params_ptr,
len(array_params),
data_array_lengths_ptr,
labels_c_array,
arrays_c_array)
return c.byref(op_values)
def _get_operations_pointers(operations_stack):
num_of_ops = len(operations_stack)
structs_ptr_array_type = c.c_void_p * num_of_ops
structs_ptr_array_obj = structs_ptr_array_type()
structs_array = []
for op in operations_stack:
if op["_OperationIdentifier"] == SpinOperations.OPERATION__THERMAL_POPULATE:
structs_array.append(_create_c_operation(op["_OperationIdentifier"], [], [op['Bx'],op['By'],op['Bz'],op['T']], {}))
elif op["_OperationIdentifier"] == SpinOperations.OPERATION__TIP_SPINS:
structs_array.append(_create_c_operation(op["_OperationIdentifier"],[_direction_str_to_int(op['direction'])], [op['BVsTArea']], {}))
elif op["_OperationIdentifier"] == SpinOperations.OPERATION__SET_HAMILTONIAN:
structs_array.append(_create_c_operation(op["_OperationIdentifier"], [], [op["Bx"], op["By"], op["Bz"]], {}))
elif op["_OperationIdentifier"] == SpinOperations.OPERATION__EVOLVE_TIME_INDEPENDENT:
structs_array.append(_create_c_operation(op["_OperationIdentifier"], [op["points"],op["threads"]], [], {}))
elif op["_OperationIdentifier"] == SpinOperations.OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION:
structs_array.append(_create_c_operation(op["_OperationIdentifier"], [_direction_str_to_int(op['measurementDirection'])], [op["samplingRate"]], {}))
elif op["_OperationIdentifier"] == SpinOperations.OPERATION__EVOLVE_TIME_DEPENDENT:
structs_array.append(_create_c_operation(op["_OperationIdentifier"],
[op["threads"], op['dirs_to_store']['x'], op['dirs_to_store']['y'],
op['dirs_to_store']['z']], [op['samplingRate']], op["input"]))
return structs_array
def _get_signal_c_call(parameters):
structs_array = _get_operations_pointers(parameters['spinOperations'].operations_stack)
operations_stack = parameters['spinOperations'].operations_stack
num_of_ops = len(operations_stack)
structs_ptr_array_type = c.c_void_p * num_of_ops
structs_ptr_array_obj = structs_ptr_array_type()
# print(structs_ptr_array_obj)
# This next loop cannot be included in the function _get_operations_pointers
# because taking c-pointers to structs_array elements doesn't make python preserve them, which causes them to
# be deleted when exiting the function
for i in range(len(structs_array)):
structs_ptr_array_obj[i] = c.cast(structs_array[i], c.c_void_p)
gammas = parameters['gyromagneticRatios']
mults = parameters['spinMultiplicities']
j_couplings = _convert_j_couplings_to_1d_array(parameters['jCouplings'])
gammas_c_version = (c.c_double * len(gammas))(*gammas)
gammas_ptr = c.cast(gammas_c_version, c.POINTER(c.c_double * len(gammas)))
if mults is None:
mults_ptr = c.c_void_p(None)
else:
mults_c_version = (c.c_int * len(mults))(*mults)
mults_ptr = c.cast(mults_c_version, c.POINTER(c.c_int * len(mults)))
if j_couplings == []:
j_couplings_ptr = c.c_void_p(None)
else:
j_couplings_c_version = (c.c_double * len(j_couplings))(*j_couplings)
j_couplings_ptr = c.cast(j_couplings_c_version, c.POINTER(c.c_double * len(j_couplings)))
mylib = c.CDLL(_SpintrumLibPath)
num_of_points = parameters['spinOperations'].total_num_of_points
return_array_type = c.c_double * num_of_points
returned_array_ptr_type = c.POINTER(return_array_type)
return_array = return_array_type()
returned_array_ptr = c.byref(return_array)
prototype = c.CFUNCTYPE(
c.c_long, # return type
c.c_void_p,
c.c_void_p,
c.c_void_p,
c.c_void_p,
c.c_int,
c.c_int,
c.c_long,
returned_array_ptr_type
)
create_signal_function = prototype(('SimulateSignal', mylib))
res = create_signal_function(structs_ptr_array_obj,
gammas_ptr,
j_couplings_ptr,
mults_ptr,
c.c_int(len(gammas)),
c.c_int(len(structs_ptr_array_obj)),
c.c_long(num_of_points),
returned_array_ptr)
# print(res)
output = np.array(c.cast(returned_array_ptr,returned_array_ptr_type).contents)
# print(output)
return output
def _convert_j_couplings_to_1d_array(j_couplings):
if j_couplings is None:
return []
output_array = []
for i in range(len(j_couplings)):
output_array += j_couplings[i][i + 1:len(j_couplings)]
return output_array
def _get_derivative(params, param_index, fitted_function, epsilon=np.sqrt(np.finfo(float).eps)):
"""
Calculates the derivatives of the fitted function (after having fitted a function) to some model
:param params: list of parameter values at the point where the derivative has to be calculated
:param param_index: index of the parameter, for which the derivative has to be taken
:param fitted_function: the function, for which the derivative has to be calculated, where
this function has to take "params" as an argument
:param epsilon: the small step to calculate the numerical difference; the default value uses Python floats' epislon
:return: the derivative value of the i-th parameter in params in the function fitted_function
"""
h = params[param_index] * epsilon
low_point__1 = np.delete(np.insert(params, param_index, params[param_index] - h), param_index + 1)
high_point_1 = np.delete(np.insert(params, param_index, params[param_index] + h), param_index + 1)
low_point__2 = np.delete(np.insert(params, param_index, params[param_index] - 2 * h), param_index + 1)
high_point_2 = np.delete(np.insert(params, param_index, params[param_index] + 2 * h), param_index + 1)
low_point__3 = np.delete(np.insert(params, param_index, params[param_index] - 3 * h), param_index + 1)
high_point_3 = np.delete(np.insert(params, param_index, params[param_index] + 3 * h), param_index + 1)
func_value_lp1 = fitted_function(low_point__1)
func_value_hp1 = fitted_function(high_point_1)
func_value_lp2 = fitted_function(low_point__2)
func_value_hp2 = fitted_function(high_point_2)
func_value_lp3 = fitted_function(low_point__3)
func_value_hp3 = fitted_function(high_point_3)
derivative = 1.5*(func_value_hp1['y'] - func_value_lp1['y'])/(2*h) - \
0.6*(func_value_hp2['y'] - func_value_lp2['y'])/(4*h) + \
0.1*(func_value_hp3['y'] - func_value_lp3['y'])/(6*h)
return derivative
def get_correlation_matrix(optimum_params, fitted_function, objective_function):
"""
A function that calculates the correlation matrix according to the book:
Wolberg 2005: Data analysis using least-squares method
:param optimum_params: list of optimum fitted parameters
:param fitted_function: function that is fitted, that takes optimum_params as a parameter
:param objective_function: the objective function used to fit. It should take optimum_params as parameter
:return: the correlation matrix calculated
"""
n = len(optimum_params) # number of parameters
p = len(fitted_function(optimum_params)['x']) # number of fitted points
min_obj_func_val = objective_function(optimum_params) # minimum objective_function value
derivatives_matrix = \
[_get_derivative(optimum_params, i, fitted_function).tolist() for i in range(len(optimum_params))]
derivatives_matrix_high_precision = mpmath.matrix(derivatives_matrix)
c_matrix = derivatives_matrix_high_precision*derivatives_matrix_high_precision.T
factor = (min_obj_func_val**2/(p-n))
correlation_matrix = (c_matrix**-1)*factor
return correlation_matrix
def get_errorbars(matrix):
error_bars = np.array([])
for i in range(matrix.cols):
error_bars = np.append(error_bars, np.float(np.sqrt(matrix[i,i])))
return error_bars
class AtomicSpecies:
GyromagneticRatio = None
Name = None
@staticmethod
def _get_species_class_list():
return AtomicSpecies.__subclasses__()
@staticmethod
def get_species_names():
return list([cls.Name for cls in AtomicSpecies._get_species_class_list()])
@staticmethod
def get_species_gyromagnetic_ratios():
return dict({cls.Name: cls.GyromagneticRatio for cls in AtomicSpecies._get_species_class_list()})
@staticmethod
def get_species_list_gyromagnetic_ratios(listOfNames):
gyromagnetic_ratios = dict({cls.Name: cls.GyromagneticRatio for cls in AtomicSpecies._get_species_class_list()})
output = []
for atom in listOfNames:
output.append(gyromagnetic_ratios[atom])
return output
def __init(self):
pass
class AtomC13(AtomicSpecies):
Name = "C13"
GyromagneticRatio = 1070.8
def __init__(self):
AtomicSpecies.__init__(self)
class AtomH1(AtomicSpecies):
Name = "H1"
GyromagneticRatio = 4257.7
def __init__(self):
AtomicSpecies.__init__(self)
class SpinSimulator:
def __init__(self, **kwargs):
self._is_initialized = False
self._spin_operations = None
self.init(kwargs)
def init(self,parameters):
# pointer to object
self.c_spin_ptr_to_object_type = c.c_void_p
# pointer to pointer to object. Necessary to modify the pointer to object
self.c_spin_ptr_to_ptr_type = c.POINTER(self.c_spin_ptr_to_object_type)
self.c_spin_ptr_to_object = self.c_spin_ptr_to_object_type()
self.c_spin_ptr_to_ptr = c.byref(self.c_spin_ptr_to_object)
argument_types = {'gyromagneticRatios': list, 'jCouplings': list, 'doPrint': bool}
must_exist_arguments = ['gyromagneticRatios']
optional_arguments = ['jCouplings', 'spinMultiplicities', 'doPrint']
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
if 'jCouplings' not in parameters:
parameters['jCouplings'] = None
if 'spinMultiplicities' not in parameters:
parameters['spinMultiplicities'] = None
_check_j_couplings_sanity(parameters['jCouplings'])
if parameters['spinMultiplicities'] is not None and \
len(parameters['gyromagneticRatios']) != len(parameters['spinMultiplicities']):
_raise_error("Spin multiplicities must have a length equal to the gyromagnetic ratios, "
"or alternatively, if you keep it empty, then it is assumed that all spins are 1/2")
gammas = parameters['gyromagneticRatios']
mults = parameters['spinMultiplicities']
jCouplings = _convert_j_couplings_to_1d_array(parameters['jCouplings'])
gammas_c_version = (c.c_double * len(gammas))(*gammas)
gammas_ptr = c.cast(gammas_c_version, c.POINTER(c.c_double * len(gammas)))
if mults is None:
mults_ptr = c.c_void_p(None)
else:
mults_c_version = (c.c_int * len(mults))(*mults)
mults_ptr = c.cast(mults_c_version, c.POINTER(c.c_int * len(mults)))
if jCouplings == []:
jCouplings_ptr = c.c_void_p(None)
else:
jCouplings_c_version = (c.c_double * len(jCouplings))(*jCouplings)
jCouplings_ptr = c.cast(jCouplings_c_version, c.POINTER(c.c_double * len(jCouplings)))
mylib = c.CDLL(_SpintrumLibPath)
prototype = c.CFUNCTYPE(
c.c_int, # return type
c.c_void_p,
c.c_void_p,
c.c_void_p,
c.c_int,
c.c_bool,
self.c_spin_ptr_to_ptr_type
)
initSimulatorCreatorFunction = prototype(('InitializeSimulator', mylib))
res = initSimulatorCreatorFunction(gammas_ptr,
jCouplings_ptr,
mults_ptr,
c.c_int(len(gammas)),
parameters['doPrint'],
self.c_spin_ptr_to_ptr)
if res >= 0:
self._is_initialized = True
else:
self._is_initialized = False
_raise_error("An error occurred while initializing the spin simulator. Possibly a memory issue.")
return res
def update_parameters(self,**parameters):
argument_types = {'gyromagneticRatios': list, 'jCouplings': list,
'spinOperations': SpinOperations}
must_exist_arguments = []
optional_arguments = ['gyromagneticRatios',
'spinOperations', 'jCouplings']
_check_elements_exist_in_dict(parameters, must_exist_arguments, optional_arguments)
_check_dict_elements_types(parameters, argument_types)
there_are_gammas = False
there_are_j_couplings = False
there_are_spin_operations = False
if 'gyromagneticRatios' in parameters:
gammas = parameters['gyromagneticRatios']
gammas_c_version = (c.c_double * len(gammas))(*gammas)
gammas_ptr = c.cast(gammas_c_version, c.POINTER(c.c_double * len(gammas)))
there_are_gammas = True
if 'jCouplings' in parameters:
_check_j_couplings_sanity(parameters['jCouplings'])
jCouplings = _convert_j_couplings_to_1d_array(parameters['jCouplings'])
jCouplings_c_version = (c.c_double * len(jCouplings))(*jCouplings)
jCouplings_ptr = c.cast(jCouplings_c_version, c.POINTER(c.c_double * len(jCouplings)))
there_are_j_couplings = True
if 'spinOperations' in parameters:
spin_ops = parameters['spinOperations']
there_are_spin_operations = True
if there_are_gammas or there_are_j_couplings:
mylib = c.CDLL(_SpintrumLibPath)
prototype = c.CFUNCTYPE(
c.c_int, # return type
c.c_void_p,
c.c_void_p
)
#set gammas values
if there_are_gammas:
set_gammas_function = prototype(('SetGammasInSimulator', mylib))
res = set_gammas_function(gammas_ptr,
self.c_spin_ptr_to_object)
if res >= 0:
pass
else:
_raise_error("An error was found while trying to set gamma values.")
# set j-couplings values
if there_are_j_couplings:
set_j_couplings_function = prototype(('SetJCouplingsInSimulator', mylib))
res = set_j_couplings_function(jCouplings_ptr,
self.c_spin_ptr_to_object)
if res >= 0:
pass
else:
_raise_error("An error was found while trying to set j-couplings values.")
if there_are_spin_operations:
self._spin_operations = spin_ops
def simulate(self):
if self._spin_operations is None:
_raise_error("SpinOperations not initialized. Use update_parameters() and set spinOperations.")
structs_array = _get_operations_pointers(self._spin_operations.operations_stack)
num_of_ops = len(self._spin_operations.operations_stack)
structs_ptr_array_type = c.c_void_p * num_of_ops
structs_ptr_array_obj = structs_ptr_array_type()
for i in range(len(structs_array)):
structs_ptr_array_obj[i] = c.cast(structs_array[i], c.c_void_p)
mylib = c.CDLL(_SpintrumLibPath)
num_of_points = self._spin_operations.total_num_of_points
returnArrayType = c.c_double * num_of_points
returnedArrayPtrType = c.POINTER(returnArrayType)
returnArray = returnArrayType()
returnedArrayPtr = c.byref(returnArray)
prototype = c.CFUNCTYPE(
c.c_long, #return type
self.c_spin_ptr_to_object_type,
c.c_void_p,
c.c_int,
c.c_long,
returnedArrayPtrType
)
createSpectFunction = prototype(('CreateSignalFromInitializedSimulator', mylib))
res = createSpectFunction(self.c_spin_ptr_to_object,
structs_ptr_array_obj,
c.c_int(len(structs_ptr_array_obj)),
c.c_long(num_of_points),
returnedArrayPtr)
# print(res)
output = np.array(c.cast(returnedArrayPtr,returnedArrayPtrType).contents)
# print(output)
return output
def __del__(self):
# print("System initialization state: " + str(self._is_initialized))
if self._is_initialized:
mylib = c.CDLL(_SpintrumLibPath)
prototype = c.CFUNCTYPE(
c.c_int, # return type
c.c_void_p
)
deinitSimulatorFunction = prototype(('DenitializeSimulator', mylib))
res = deinitSimulatorFunction(self.c_spin_ptr_to_object)
if res >= 0:
self._is_initialized = False
else:
_raise_error("An error was found while trying to free the memory.")

358
src/Spintrum.cpp Normal file
View File

@ -0,0 +1,358 @@
#ifdef _MSC_VER //If the compiler is the Visual Studio Compiler
#define NOMINMAX //solves a problem with std::max on Windows
#pragma warning(disable: 4297) //remove throw warnings
#endif
#include "common/definitions.h"
#include <iostream>
#include <vector>
#include "common/SpinSystem.h"
const bool debug = false;
const char* get_version()
{
return SPINTRUM_VERSION;
}
void print_software_info()
{
std::cout<<"Spintrum version "<<get_version()<<". ";
std::cout<<"This software is provided under the MPL license. "
"For more information, contact Samer Afach: samer@afach.de."<<std::endl<<std::endl;
}
/**
* A quantum mechanics operation (populate spins, tip spins, etc...) is a struct that contains a specific, predefined number of parameters.
* Each operation has an Identifier, which is simply an integer. From this identifier, the code knows what parameters to seek
* and how many parameters should be expected.
* There are integer parameters, real parameters, and array of real parameters.
*/
struct SpinOperation
{
long OperationIdentifier;
long Params_int_count; //number of integer parameters
long* Params_int; //integer parameters
long Params_real_count; //number of real parameters
double* Params_real; //real parameters
long Params_array_count; //number of arrays
long* Params_array_lengths; //lengths of suppled arrays
char** Params_array_names; //names of the parameters of the arrays
double** Params_array; //array data
};
const static int OPERATION__THERMAL_POPULATE = 0;
const static int OPERATION__TIP_SPINS = 1;
const static int OPERATION__SET_HAMILTONIAN = 2;
const static int OPERATION__EVOLVE_TIME_INDEPENDENT = 3;
const static int OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION = 4;
const static int OPERATION__EVOLVE_TIME_DEPENDENT = 5;
typedef double Real;
typedef SpinSystem<Real,std::complex<Real>,VEC,CX_VEC,MAT,CX_MAT> SpinSystemType;
struct SpinInfo
{
CX_MAT jCouplings;
CX_VEC gammas;
G_MAT<int> multiplicities;
};
void devectorizeJCouplings(const long numOfSpins, const double* const jCouplingsInput, CX_MAT& jCouplingsOutput)
{
if(jCouplingsInput == 0)
{
jCouplingsOutput.resize(0,0);
return;
}
int i = 0; //element of given array
int j = 0; //element of current row
int row = 0;
while (i < numOfSpins*(numOfSpins-1)/2)
{
if(j <= row)
{
j++;
continue;
}
if(j >= numOfSpins)
{
j = 0;
row++;
continue;
}
jCouplingsOutput.at(row,j) = jCouplingsInput[i];
j++;
i++;
}
}
extern "C" int InitializeSimulator(double* gammas, double* jCouplings, int* spinMultiplicities, int numOfSpins, bool doPrintOutput, void** SpinSystemObject)
{
try
{
print_software_info();
// std::cout<<"Number of spins: "<<numOfSpins<<std::endl;
SpinInfo spinInfo;
spinInfo.gammas.resize(numOfSpins,1);
spinInfo.multiplicities.resize(numOfSpins,1);
spinInfo.jCouplings.resize(numOfSpins,numOfSpins);
for(int i = 0; i < numOfSpins; i++)
{
// std::cout<<gammas[i]<<"\t";
spinInfo.gammas[i] = gammas[i];
}
// std::cout<<spinInfo.gammas<<std::endl;
if(spinMultiplicities == 0)
{
for(int i = 0; i < numOfSpins; i++)
spinInfo.multiplicities[i] = 2;
}
else
{
for(int i = 0; i < numOfSpins; i++)
spinInfo.multiplicities[i] = spinMultiplicities[i];
}
devectorizeJCouplings(numOfSpins, jCouplings, spinInfo.jCouplings);
// std::cout<<spinInfo.jCouplings<<std::endl;
SpinSystemType *Spins = new SpinSystem<Real,std::complex<Real>,VEC,CX_VEC,MAT,CX_MAT>();
Spins->print = doPrintOutput;
Spins->init(spinInfo.gammas,spinInfo.jCouplings,spinInfo.multiplicities);
*SpinSystemObject = static_cast<void*>(Spins);
return 0;
}
catch(std::exception &ex)
{
std::cout<<"An exception was thrown while trying to initialize the spin system. Exception message is: " << ex.what() << std::endl;
return -1;
}
catch(...)
{
std::cout<<"An unhandled exception was thrown while trying to initialize the spin system."<< std::endl;
return -2;
}
}
extern "C" int DenitializeSimulator(void* SpinSystemObject)
{
try
{
delete (static_cast<SpinSystemType*>(SpinSystemObject));
return 0;
}
catch(std::exception &ex)
{
std::cout<<"An exception was thrown while trying to delete the spin system from memory. Exception message is: " << ex.what() << std::endl;
return -1;
}
catch(...)
{
std::cout<<"An unhandled exception was thrown while trying to delete the spin system from memory."<< std::endl;
return -2;
}
}
extern "C" int SetGammasInSimulator(double* gammas, void* SpinSystemObject)
{
try
{
CX_VEC gammasVec((static_cast<SpinSystemType*>(SpinSystemObject))->getNumOfSpins(),1);
for(int i = 0; i < gammasVec.size(); i++)
{
gammasVec[i] = gammas[i];
}
(static_cast<SpinSystemType*>(SpinSystemObject))->setGammas(gammasVec);
return 0;
}
catch(std::exception &ex)
{
std::cout<<"An exception was thrown while trying to delete the spin system from memory. Exception message is: " << ex.what() << std::endl;
return -1;
}
catch(...)
{
std::cout<<"An unhandled exception was thrown while trying to delete the spin system from memory."<< std::endl;
return -2;
}
}
extern "C" int SetJCouplingsInSimulator(double* jCouplings, void* SpinSystemObject)
{
try
{
CX_MAT jCouplingsMat((static_cast<SpinSystemType*>(SpinSystemObject))->getNumOfSpins(),(static_cast<SpinSystemType*>(SpinSystemObject))->getNumOfSpins());
devectorizeJCouplings((static_cast<SpinSystemType*>(SpinSystemObject))->getNumOfSpins(), jCouplings, jCouplingsMat);
(static_cast<SpinSystemType*>(SpinSystemObject))->setJCouplings(jCouplingsMat);
return 0;
}
catch(std::exception &ex)
{
std::cout<<"An exception was thrown while trying to delete the spin system from memory. Exception message is: " << ex.what() << std::endl;
return -1;
}
catch(...)
{
std::cout<<"An unhandled exception was thrown while trying to delete the spin system from memory."<< std::endl;
return -2;
}
}
void _do_operation_evolve_time_dependent(SpinOperation* op, SpinSystemType* SpinsPtr, double* outputArray, long &currentDataPoint)
{
if(debug) std::cout<<"Printing received data:"<<std::endl;
if(op->Params_array_count == 0)
{
throw std::runtime_error("There's no data provided for the time-dependent evolution.");
}
else
{
//make sure that all lengths are equal
long initialLength = op->Params_array_lengths[0];
for(long i = 1; i < op->Params_array_count; i++)
{
if(op->Params_array_lengths[i] != initialLength)
{
throw std::length_error("Data arrays in time-dependent evolution are expected all to be of the same length.");
}
}
}
std::vector<std::string> varsNames(static_cast<std::vector<std::string>::size_type>(op->Params_array_count));
std::copy(op->Params_array_names,op->Params_array_names+op->Params_array_count,varsNames.begin()); //copy names to vector<string>
CX_MAT evData(op->Params_array_lengths[0],op->Params_array_count);
for(long i = 0; i < op->Params_array_count; i++)
{
std::copy(&op->Params_array[i][0],&op->Params_array[i][op->Params_array_lengths[i]],evData.begin()+evData.rows()*i);
}
std::set<char> dirString;
if(op->Params_int[1]) dirString.insert('x');
if(op->Params_int[2]) dirString.insert('y');
if(op->Params_int[3]) dirString.insert('z');
std::vector<Real> tr = SpinsPtr->evolveDensityMatrix(op->Params_real[0],varsNames,evData,static_cast<int>(op->Params_int[0]),dirString);
std::copy(std::make_move_iterator(tr.begin()), std::make_move_iterator(tr.end()), outputArray + currentDataPoint);
currentDataPoint += op->Params_array_lengths[0]*static_cast<long>(dirString.size());
}
long ExecuteOperations(void* SpinSystemObject, void** ops, int numOfOperations, double* output, bool debug)
{
if(debug)
{
std::cout<<"Number of operations: "<<numOfOperations<<std::endl;
}
SpinSystemType* SpinsPtr = static_cast<SpinSystemType*>(SpinSystemObject);
long currentDataPoint = 0; //for a simulation with many operations that consecutively fill the output, this keeps track of the current point
for(int i = 0; i < numOfOperations; i++) {
void** currOperationBytePosition = (static_cast<void**>(ops));
long OperationIdentifier = *(static_cast<long*>(currOperationBytePosition[i]));
if(debug) std::cout<<"Identifier: "<<OperationIdentifier<<std::endl;
if(OperationIdentifier == OPERATION__THERMAL_POPULATE) {
SpinOperation* op;
op = static_cast<SpinOperation*>(currOperationBytePosition[i]);
SpinsPtr->populate_thermal(op->Params_real[0],op->Params_real[1],op->Params_real[2],op->Params_real[3]);
}
else if (OperationIdentifier == OPERATION__TIP_SPINS) {
SpinOperation* op;
op = static_cast<SpinOperation*>(currOperationBytePosition[i]);
SpinsPtr->tipSpins(static_cast<int>(op->Params_int[0]),op->Params_real[0]);
}
else if (OperationIdentifier == OPERATION__SET_HAMILTONIAN) {
SpinOperation* op;
op = static_cast<SpinOperation*>(currOperationBytePosition[i]);
SpinsPtr->calculateHamiltonians(op->Params_real[0],op->Params_real[1],op->Params_real[2]);
}
else if (OperationIdentifier == OPERATION__EVOLVE_TIME_INDEPENDENT) {
SpinOperation* op;
op = static_cast<SpinOperation*>(currOperationBytePosition[i]);
std::vector<Real> trVals = SpinsPtr->solveMagnetization_parallel(op->Params_int[0],static_cast<int>(op->Params_int[1]));
std::copy(trVals.begin(), trVals.end(), output + currentDataPoint);
currentDataPoint += op->Params_int[0];
}
else if (OperationIdentifier == OPERATION__INIT_TIME_INDEPENDENT_EVOLUTION) {
SpinOperation* op;
op = static_cast<SpinOperation*>(currOperationBytePosition[i]);
SpinsPtr->initTimeIndependentEvolution(op->Params_real[0],static_cast<int>(op->Params_int[0]));
}
else if (OperationIdentifier == OPERATION__EVOLVE_TIME_DEPENDENT) {
_do_operation_evolve_time_dependent(static_cast<SpinOperation*>(currOperationBytePosition[i]), SpinsPtr, output, currentDataPoint);
}
else {
std::cout << "Error: An unknown operation was requested... Exiting." << std::endl;
exit(1);
}
}
return currentDataPoint;
}
extern "C" long CreateSignalFromInitializedSimulator(void* SpinSystemObject, void** ops, int numOfOperations, long numOfPoints, double* output)
{
try {
if(debug)
{
std::cout<<"Number of operations: "<<numOfOperations<<std::endl;
std::cout<<"Number of points: "<<numOfPoints<<std::endl;
}
long processedNumOfPoints = ExecuteOperations(SpinSystemObject,ops,numOfOperations,output,debug);
if (debug) std::cout<<processedNumOfPoints<<std::endl;
return processedNumOfPoints;
}
catch(std::exception& ex) {
std::cerr << "An exception was thrown by Spintrum. It says: " << ex.what() << std::endl;
return 0;
}
catch(...) {
std::cerr << "An unknown exception was thrown by Spintrum. " << std::endl;
return 0;
}
}
void _fill_spin_info(int numOfSpins, double* gammas, double* jCouplings, int* spinMultiplicities, SpinInfo& spinInfo)
{
spinInfo.gammas.resize(numOfSpins,1);
spinInfo.multiplicities.resize(numOfSpins,1);
spinInfo.jCouplings.resize(numOfSpins,numOfSpins);
for(int i = 0; i < numOfSpins; i++) {
spinInfo.gammas[i] = gammas[i];
}
if(spinMultiplicities == 0) {
for(int i = 0; i < numOfSpins; i++)
spinInfo.multiplicities[i] = 2;
}
else {
for(int i = 0; i < numOfSpins; i++)
spinInfo.multiplicities[i] = spinMultiplicities[i];
}
if(debug) std::cout<<"Gammas:"<<std::endl;
if(debug) std::cout<<spinInfo.gammas<<std::endl;
devectorizeJCouplings(numOfSpins, jCouplings, spinInfo.jCouplings);
if(debug) std::cout<<"J-couplings:"<<std::endl;
if(debug) std::cout<<spinInfo.jCouplings<<std::endl;
}
extern "C" long SimulateSignal(void** ops, double* gammas, double* jCouplings, int* spinMultiplicities, int numOfSpins, int numOfOperations, long numOfPoints, double* output)
{
try {
print_software_info();
if(debug) {
std::cout<<"Number of operations: "<<numOfOperations<<std::endl;
std::cout<<"Number of points: "<<numOfPoints<<std::endl;
std::cout<<"Number of spins: "<<numOfSpins<<std::endl;
}
SpinInfo spinInfo;
_fill_spin_info(numOfSpins, gammas, jCouplings, spinMultiplicities, spinInfo);
SpinSystem<Real,std::complex<Real>,VEC,CX_VEC,MAT,CX_MAT > Spins(spinInfo.gammas,spinInfo.jCouplings,spinInfo.multiplicities);
long processedNumOfPoints = ExecuteOperations(static_cast<void*>(&Spins),ops,numOfOperations,output,debug);
if (debug) std::cout<<processedNumOfPoints<<std::endl;
return processedNumOfPoints;
}
catch(std::exception& ex) {
std::cerr << "An exception was thrown by Spintrum. It says: " << ex.what() << std::endl;
return 0;
}
catch(...) {
std::cerr << "An unknown exception was thrown by Spintrum. " << std::endl;
return 0;
}
}