Giter VIP home page Giter VIP logo

mrsimulator's People

Contributors

code-factor avatar deepanshs avatar dependabot[bot] avatar mccarthy677 avatar mgiammar avatar mvenetos97 avatar pjgrandinetti avatar shyamd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mrsimulator's Issues

Add a `rotate` function to the `Site` class

A new Site class function

def rotate(self, Euler_angles):
    """Rotate the site tensor (shielding, quad, J, and Dipolar) by the given Euler angle rotation"""
    return rotated_site

Method should raise an exception when two or more events have non-zero or non-inf rotor_frequency.

Bug report

Method should raise exception

To Reproduce

from mrsimulator.method import Method, SpectralDimension
from mrsimulator.method.event import SpectralEvent


my_method = Method(
    channels=["87Rb"],
    magnetic_flux_density=9.4,
    rotor_frequency=10000,  # in Hz
    spectral_dimensions=[
        SpectralDimension(
            count=128,
            spectral_width=6e3,  # in Hz
            reference_offset=-9e3,  # in Hz
            label="Symmetric 3Q Frequency",
            events=[SpectralEvent(transition_query=[{"ch1": {"P": [-3], "D": [0]}}])],
        ),
        SpectralDimension(
            count=256,
            spectral_width=6e3,  # in Hz
            reference_offset=-5e3,  # in Hz
            label="Central Transition Frequency",
            events=[SpectralEvent(transition_query=[{"ch1": {"P": [-1], "D": [0]}}])],
        ),
    ],
)

Runs without any exception

Expected behavior

Raise an exception because the method has two events with 10 kHz rotor_frequency.

Additional context

  • mrsimulator version: 0.7.0rc2

Testing: Use pytest

Tests appear to be written as prints as part of guarded main functions. Switch to something like pytest with travis CI auto-testing.

Add a linear interpolation scheme for probability distribution approximation

Linear interpolation scheme for gridding Czjzek/Extended Czjzek/User-defined distributions.

The current implementation of the probability distribution uses np.histogram2d function to grid 400000 samples (default) over a two-dimensional grid. The histogram function generates a discrete non-continuous distribution which is okay for one-time calculation but is not optimal when used iteratively in a least-squares problem.

Proposed Solution
Use linear interpolation approximation to generate a smooth and continuous probability distribution.

Add a new `CustomIsotope` class.

class CustomIsotope:
   symbol: str
   spin: int
   natural_abundance: float
   gyromagnetic_ratio: float
   quadrupole_moment: float
   atomic_number: int
  • Check serialization and reading custom isotopes.

Add a custom EulerAngles class

Include EulerAngles class in mrsimulator

class EulerAngles:
    alpha: float
    beta: float
    gamma: float

Define a method __add__ to add two Euler angle.

e1 = EulerAngles(alpha=0.5, beta=3.14, gamma=1.14)
e2 = EulerAngles(alpha=1.2, beta=1.23, gamma=-2.0)
e3 = e1 + e2

Release note for v0.7

Create a release note (changelog) for the v0.7 release about breaking changes and fixes

Add to the following list

  • mrsimulator.signal_processing -> mrsimulator.signal_processor

Deprecation warning for `from mrsimulator.methods import ....`

Add deprecation warning when user imports library methods using from mrsimulator.methods import ....

DeprecationWarning should say that using the methods module will result in an error in v0.8 and up.

Add a methods.py file and load the method.lib class in there for v0.7 to retain backward compatibility. We will remove this file in v0.8. The purpose of this file is only to warn users.

Create conda recipe for mrsimulator

We are having some issues with the binary distribution of the mrsimulator package for windows. An alternative is to look into writing a conda recipe for mrsimulator installation.

'MixingEnum' object has no attribute 'json'

Mixing Enum has no attribute json

To reproduce

mth = Method(
    channels=["1H"],
    magnetic_flux_density=9.4,
    spectral_dimensions=[SpectralDimension(
        count=1024,
        spectral_width=2e6,
        events=[
            SpectralEvent(transition_queries=[{"ch1": {"P": [-1]}}]),
            MixingEvent(query=MixingEnum.NoMixing),
            SpectralEvent(transition_queries=[{"ch1": {"P": [-1]}}])
        ]
    )]
)
mth.json()

Building library from source errors out

Did you find a bug? Please help us improve by fill out the sections below. 👍

Describe the bug

Running pip install -e . results in a long error relating to the file /pyproject.toml:

Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: /Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/bin/python /Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py prepare_metadata_for_build_wheel /var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/tmp6n7cyehk
         cwd: /Users/mgiammar/Documents/Python/mrsimulator
    Complete output (526 lines):
    Using python version 3.9.2
    mrsimulator version  0.7.0rc1
    Attempting to link mrsimulator with the openblas library.
    Attempting to link mrsimulator with the fftw library.
    ['/opt/homebrew/opt/openblas/include', '/usr/local/opt/openblas/include', '/usr/local/opt/fftw/include', '/opt/homebrew/opt/fftw/include', 'src/c_lib/include/', '/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/numpy/core/include']
    ['/usr/local/opt/fftw/lib', '/opt/homebrew/opt/openblas/lib', '/opt/homebrew/opt/fftw/lib', '/usr/local/opt/openblas/lib']
    ['fftw3', 'openblas']
    ['-O3', '-fvectorize', '-fcommon', '-ffast-math', '-DUSE_OPENBLAS']
    ['-lm']
    /private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/config/pyprojecttoml.py:100: _ExperimentalProjectMetadata: Support for project metadata in `pyproject.toml` is still experimental and may be removed (or change) in future releases.
      warnings.warn(msg, _ExperimentalProjectMetadata)
    configuration error: `project` must contain ['name'] properties
    DESCRIPTION:
        Data structure for the **project** table inside ``pyproject.toml`` (as
        initially defined in :pep:`621`)
    
    GIVEN VALUE:
        {
            "requires-python": ">=3.6"
        }
    
    OFFENDING RULE: 'required'
    
    DEFINITION:
        {
            "$schema": "http://json-schema.org/draft-07/schema",
            "$id": "https://packaging.python.org/en/latest/specifications/declaring-project-metadata/",
            "title": "Package metadata stored in the ``project`` table",
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "The name (primary identifier) of the project. MUST be statically defined.",
                    "format": "pep508-identifier"
                },
                "version": {
                    "type": "string",
                    "description": "The version of the project as supported by :pep:`440`.",
                    "format": "pep440"
                },
                "description": {
                    "type": "string",
                    "$$description": [
                        "The `summary description of the project",
                        "<https://packaging.python.org/specifications/core-metadata/#summary>`_"
                    ]
                },
                "readme": {
                    "$$description": [
                        "`Full/detailed description of the project in the form of a README",
                        "<https://www.python.org/dev/peps/pep-0621/#readme>`_",
                        "with meaning similar to the one defined in `core metadata's Description",
                        "<https://packaging.python.org/specifications/core-metadata/#description>`_"
                    ],
                    "oneOf": [
                        {
                            "type": "string",
                            "$$description": [
                                "Relative path to a text file (UTF-8) containing the full description",
                                "of the project. If the file path ends in case-insensitive ``.md`` or",
                                "``.rst`` suffixes, then the content-type is respectively",
                                "``text/markdown`` or ``text/x-rst``"
                            ]
                        },
                        {
                            "type": "object",
                            "allOf": [
                                {
                                    "anyOf": [
                                        {
                                            "properties": {
                                                "file": {
                                                    "type": "string",
                                                    "$$description": [
                                                        "Relative path to a text file containing the full description",
                                                        "of the project."
                                                    ]
                                                }
                                            },
                                            "required": [
                                                "file"
                                            ]
                                        },
                                        {
                                            "properties": {
                                                "text": {
                                                    "type": "string",
                                                    "description": "Full text describing the project."
                                                }
                                            },
                                            "required": [
                                                "text"
                                            ]
                                        }
                                    ]
                                },
                                {
                                    "properties": {
                                        "content-type": {
                                            "type": "string",
                                            "$$description": [
                                                "Content-type (:rfc:`1341`) of the full description",
                                                "(e.g. ``text/markdown``). The ``charset`` parameter is assumed",
                                                "UTF-8 when not present."
                                            ],
                                            "$comment": "TODO: add regex pattern or format?"
                                        }
                                    },
                                    "required": [
                                        "content-type"
                                    ]
                                }
                            ]
                        }
                    ]
                },
                "requires-python": {
                    "type": "string",
                    "format": "pep508-versionspec",
                    "$$description": [
                        "`The Python version requirements of the project",
                        "<https://packaging.python.org/specifications/core-metadata/#requires-python>`_."
                    ]
                },
                "license": {
                    "description": "`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.",
                    "oneOf": [
                        {
                            "properties": {
                                "file": {
                                    "type": "string",
                                    "$$description": [
                                        "Relative path to the file (UTF-8) which contains the license for the",
                                        "project."
                                    ]
                                }
                            },
                            "required": [
                                "file"
                            ]
                        },
                        {
                            "properties": {
                                "text": {
                                    "type": "string",
                                    "$$description": [
                                        "The license of the project whose meaning is that of the",
                                        "`License field from the core metadata",
                                        "<https://packaging.python.org/specifications/core-metadata/#license>`_."
                                    ]
                                }
                            },
                            "required": [
                                "text"
                            ]
                        }
                    ]
                },
                "authors": {
                    "type": "array",
                    "items": {
                        "$id": "#/definitions/author",
                        "title": "Author or Maintainer",
                        "$comment": "https://www.python.org/dev/peps/pep-0621/#authors-maintainers",
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                "$$description": [
                                    "MUST be a valid email name, i.e. whatever can be put as a name, before an",
                                    "email, in :rfc:`822`."
                                ]
                            },
                            "email": {
                                "type": "string",
                                "format": "idn-email",
                                "description": "MUST be a valid email address"
                            }
                        }
                    },
                    "$$description": [
                        "The people or organizations considered to be the 'authors' of the project.",
                        "The exact meaning is open to interpretation (e.g. original or primary authors,",
                        "current maintainers, or owners of the package)."
                    ]
                },
                "maintainers": {
                    "type": "array",
                    "items": {
                        "$id": "#/definitions/author",
                        "title": "Author or Maintainer",
                        "$comment": "https://www.python.org/dev/peps/pep-0621/#authors-maintainers",
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                "$$description": [
                                    "MUST be a valid email name, i.e. whatever can be put as a name, before an",
                                    "email, in :rfc:`822`."
                                ]
                            },
                            "email": {
                                "type": "string",
                                "format": "idn-email",
                                "description": "MUST be a valid email address"
                            }
                        }
                    },
                    "$$description": [
                        "The people or organizations considered to be the 'maintainers' of the project.",
                        "Similarly to ``authors``, the exact meaning is open to interpretation."
                    ]
                },
                "keywords": {
                    "type": "array",
                    "items": {
                        "type": "string"
                    },
                    "description": "List of keywords to assist searching for the distribution in a larger catalog."
                },
                "classifiers": {
                    "type": "array",
                    "items": {
                        "type": "string",
                        "format": "trove-classifier",
                        "description": "`PyPI classifier <https://pypi.org/classifiers/>`_."
                    },
                    "$$description": [
                        "`Trove classifiers <https://pypi.org/classifiers/>`_",
                        "which apply to the project."
                    ]
                },
                "urls": {
                    "type": "object",
                    "description": "URLs associated with the project in the form ``label => value``.",
                    "additionalProperties": false,
                    "patternProperties": {
                        "^.+$": {
                            "type": "string",
                            "format": "url"
                        }
                    }
                },
                "scripts": {
                    "$id": "#/definitions/entry-point-group",
                    "title": "Entry-points",
                    "type": "object",
                    "$$description": [
                        "Entry-points are grouped together to indicate what sort of capabilities they",
                        "provide.",
                        "See the `packaging guides",
                        "<https://packaging.python.org/specifications/entry-points/>`_",
                        "and `setuptools docs",
                        "<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_",
                        "for more information."
                    ],
                    "propertyNames": {
                        "format": "python-entrypoint-name"
                    },
                    "additionalProperties": false,
                    "patternProperties": {
                        "^.+$": {
                            "type": "string",
                            "$$description": [
                                "Reference to a Python object. It is either in the form",
                                "``importable.module``, or ``importable.module:object.attr``."
                            ],
                            "format": "python-entrypoint-reference",
                            "$comment": "https://packaging.python.org/specifications/entry-points/"
                        }
                    }
                },
                "gui-scripts": {
                    "$id": "#/definitions/entry-point-group",
                    "title": "Entry-points",
                    "type": "object",
                    "$$description": [
                        "Entry-points are grouped together to indicate what sort of capabilities they",
                        "provide.",
                        "See the `packaging guides",
                        "<https://packaging.python.org/specifications/entry-points/>`_",
                        "and `setuptools docs",
                        "<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_",
                        "for more information."
                    ],
                    "propertyNames": {
                        "format": "python-entrypoint-name"
                    },
                    "additionalProperties": false,
                    "patternProperties": {
                        "^.+$": {
                            "type": "string",
                            "$$description": [
                                "Reference to a Python object. It is either in the form",
                                "``importable.module``, or ``importable.module:object.attr``."
                            ],
                            "format": "python-entrypoint-reference",
                            "$comment": "https://packaging.python.org/specifications/entry-points/"
                        }
                    }
                },
                "entry-points": {
                    "$$description": [
                        "Instruct the installer to expose the given modules/functions via",
                        "``entry-point`` discovery mechanism (useful for plugins).",
                        "More information available in the `Python packaging guide",
                        "<https://packaging.python.org/specifications/entry-points/>`_."
                    ],
                    "propertyNames": {
                        "format": "python-entrypoint-group"
                    },
                    "additionalProperties": false,
                    "patternProperties": {
                        "^.+$": {
                            "$id": "#/definitions/entry-point-group",
                            "title": "Entry-points",
                            "type": "object",
                            "$$description": [
                                "Entry-points are grouped together to indicate what sort of capabilities they",
                                "provide.",
                                "See the `packaging guides",
                                "<https://packaging.python.org/specifications/entry-points/>`_",
                                "and `setuptools docs",
                                "<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_",
                                "for more information."
                            ],
                            "propertyNames": {
                                "format": "python-entrypoint-name"
                            },
                            "additionalProperties": false,
                            "patternProperties": {
                                "^.+$": {
                                    "type": "string",
                                    "$$description": [
                                        "Reference to a Python object. It is either in the form",
                                        "``importable.module``, or ``importable.module:object.attr``."
                                    ],
                                    "format": "python-entrypoint-reference",
                                    "$comment": "https://packaging.python.org/specifications/entry-points/"
                                }
                            }
                        }
                    }
                },
                "dependencies": {
                    "type": "array",
                    "description": "Project (mandatory) dependencies.",
                    "items": {
                        "$id": "#/definitions/dependency",
                        "title": "Dependency",
                        "type": "string",
                        "description": "Project dependency specification according to PEP 508",
                        "format": "pep508"
                    }
                },
                "optional-dependencies": {
                    "type": "object",
                    "description": "Optional dependency for the project",
                    "propertyNames": {
                        "format": "pep508-identifier"
                    },
                    "additionalProperties": false,
                    "patternProperties": {
                        "^.+$": {
                            "type": "array",
                            "items": {
                                "$id": "#/definitions/dependency",
                                "title": "Dependency",
                                "type": "string",
                                "description": "Project dependency specification according to PEP 508",
                                "format": "pep508"
                            }
                        }
                    }
                },
                "dynamic": {
                    "type": "array",
                    "$$description": [
                        "Specifies which fields are intentionally unspecified and expected to be",
                        "dynamically provided by build tools"
                    ],
                    "items": {
                        "enum": [
                            "version",
                            "description",
                            "readme",
                            "requires-python",
                            "license",
                            "authors",
                            "maintainers",
                            "keywords",
                            "classifiers",
                            "urls",
                            "scripts",
                            "gui-scripts",
                            "entry-points",
                            "dependencies",
                            "optional-dependencies"
                        ]
                    }
                }
            },
            "required": [
                "name"
            ],
            "additionalProperties": false,
            "if": {
                "not": {
                    "required": [
                        "version"
                    ],
                    "$$description": [
                        "version is statically defined in the ``version`` field"
                    ]
                },
                "$$comment": [
                    "According to :pep:`621`:",
                    "    If the core metadata specification lists a field as \"Required\", then",
                    "    the metadata MUST specify the field statically or list it in dynamic",
                    "In turn, `core metadata`_ defines:",
                    "    The required fields are: Metadata-Version, Name, Version.",
                    "    All the other fields are optional.",
                    "Since ``Metadata-Version`` is defined by the build back-end, ``name`` and",
                    "``version`` are the only mandatory information in ``pyproject.toml``.",
                    ".. _core metadata: https://packaging.python.org/specifications/core-metadata/"
                ]
            },
            "then": {
                "properties": {
                    "dynamic": {
                        "contains": {
                            "const": "version"
                        },
                        "$$description": [
                            "version should be listed in ``dynamic``"
                        ]
                    }
                }
            },
            "definitions": {
                "author": {
                    "$id": "#/definitions/author",
                    "title": "Author or Maintainer",
                    "$comment": "https://www.python.org/dev/peps/pep-0621/#authors-maintainers",
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string",
                            "$$description": [
                                "MUST be a valid email name, i.e. whatever can be put as a name, before an",
                                "email, in :rfc:`822`."
                            ]
                        },
                        "email": {
                            "type": "string",
                            "format": "idn-email",
                            "description": "MUST be a valid email address"
                        }
                    }
                },
                "entry-point-group": {
                    "$id": "#/definitions/entry-point-group",
                    "title": "Entry-points",
                    "type": "object",
                    "$$description": [
                        "Entry-points are grouped together to indicate what sort of capabilities they",
                        "provide.",
                        "See the `packaging guides",
                        "<https://packaging.python.org/specifications/entry-points/>`_",
                        "and `setuptools docs",
                        "<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_",
                        "for more information."
                    ],
                    "propertyNames": {
                        "format": "python-entrypoint-name"
                    },
                    "additionalProperties": false,
                    "patternProperties": {
                        "^.+$": {
                            "type": "string",
                            "$$description": [
                                "Reference to a Python object. It is either in the form",
                                "``importable.module``, or ``importable.module:object.attr``."
                            ],
                            "format": "python-entrypoint-reference",
                            "$comment": "https://packaging.python.org/specifications/entry-points/"
                        }
                    }
                },
                "dependency": {
                    "$id": "#/definitions/dependency",
                    "title": "Dependency",
                    "type": "string",
                    "description": "Project dependency specification according to PEP 508",
                    "format": "pep508"
                }
            }
        }
    Traceback (most recent call last):
      File "/Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 349, in <module>
        main()
      File "/Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 331, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 151, in prepare_metadata_for_build_wheel
        return hook(metadata_directory, config_settings)
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 188, in prepare_metadata_for_build_wheel
        self.run_setup()
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 281, in run_setup
        super(_BuildMetaLegacyBackend,
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 174, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 409, in <module>
        setup(
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/__init__.py", line 79, in setup
        return distutils.core.setup(**attrs)
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/_distutils/core.py", line 122, in setup
        dist.parse_config_files()
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/dist.py", line 836, in parse_config_files
        pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/config/pyprojecttoml.py", line 52, in apply_configuration
        config = read_configuration(filepath, True, ignore_option_errors, dist)
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/config/pyprojecttoml.py", line 117, in read_configuration
        validate(subset, filepath)
      File "/private/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/pip-build-env-s5k_069j/overlay/lib/python3.9/site-packages/setuptools/config/pyprojecttoml.py", line 43, in validate
        raise error from None
    ValueError: invalid pyproject.toml config: `project`
    ----------------------------------------
WARNING: Discarding file:///Users/mgiammar/Documents/Python/mrsimulator. Command errored out with exit status 1: /Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/bin/python /Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py prepare_metadata_for_build_wheel /var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/tmp6n7cyehk Check the logs for full command output.
ERROR: Command errored out with exit status 1: /Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/bin/python /Users/mgiammar/opt/anaconda3/envs/mrsimulator-dev/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py prepare_metadata_for_build_wheel /var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/tmp6n7cyehk Check the logs for full command output.

To Reproduce

  1. pip uninstall mrsimulator
  2. rm -rf build
  3. pip install -e .

Expected behavior

Mrsimulator is built from source.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [macOS intel (accelerate) and M1 (BLAS)]

  • Python version: [3.9.2]

  • mrsimulator version: [0.7rc1]

Additional context

Bug in Minimizer(sf.LMFIT_min_function, fit_parameters, fcn_args=(sim, processor, sigma))

Did you find a bug? Please help us improve by fill out the sections below. 👍
When I try to fit a simulation against a simulation the Minimizer crashes
Describe the bug

AttributeError: 'numpy.ndarray' object has no attribute '_set_unit'

To Reproduce

Create a jupyter notebook
load the "Least-Squares Fitting Example" from https://mrsimulator.readthedocs.io/en/stable/introduction/fitting_example.html
I did this by cutting and pasting each cell.

Expected behavior

Fit results as on the web page

Desktop (please complete the following information):

  • OS: [Windows 10
  • Python version: [e.g. 3.7.1] 3.10.9 in Anaconda environment Anaconda3-2023.03-1-Windows-x86_64
  • mrsimulator version: [e.g. 0.3] 0.70, lmfit 1.2.1

Additional context

Add any other context about the problem here.

Helper objects for MixingEvent

  • Add new pre-build object for MixingQuery---NoMixing. NoMixing is a place holder and should expand to a mixing object as
    {'ch1': {'tip_angle': 0, 'phase': 0}, 'ch2': {'tip_angle': 0, 'phase': 0}, 'ch3': {'tip_angle': 0, 'phase': 0}}

The number of channels should adjust based on the length of method's channels attribute.

  • TotalMixing Default

Create wheel files for M1 Mac distribution

Since GitHub does not support building distributions for M1 Mac, the wheels for M1 Mac need to be build and uploaded to PyPi manually. Ideally, these .whl files will have the arm64 versions openblas and fftw already packaged in.

Simplify user-defined spin system object to irreducible spin system objects.

Consider a spin system with six sites labeled as [A, B, C, D, E, F] with 10% abundance.

  • If all sites are uncoupled, break the six-site spin system into six single-site spin systems with 10% abundance. [A], [B], [C], [D], [E], and [F]
  • If site A-B-C and D-F are coupled, break the spin system into three, three-site [A-B-C], two-site [D-F], and single-site [E].

Support for multi-dimensional (>2) SpectralDimension simulation.

The current implementation is limited to 2 spectral dimensions because of the two-dimensional powder interpolation scheme. Remove the upper bound by

  • Expanding the interpolation scheme to three or higher dimensions.
  • Otherwise, revert to a brute force spectral binning scheme.

Renaming/ reorg for v0.7 release.

  • renaming mrsimulator.methods to mrsimulator.methods_lib.
  • Remove Method1D and Method2D from stock and use generic Method for custom methods. (done in #136)

(Following in #140 )

  • Rename mixing_query from MixingQuery object to query. The current name is redundant with the object name.
  • Rename RFRotation class to RotationalQuery??
  • Rename tip_angle in RFRotation to angle?

SkewedGaussian with skew of 0 throws TypeError during application to dataset

Did you find a bug? Please help us improve by filling out the sections below. 👍

Describe the bug

A SkewedGaussian apodization object with skew=0 throws a TypeError when calling apply_oeprations()

To Reproduce

Steps to reproduce the behavior:

import csdmpy as cp
import numpy as np
from mrsimulator import signal_processing as sp

# Create signal processor object
processor = sp.SignalProcessor(
    operations=[
        sp.IFFT(),
        sp.apodization.SkewedGaussian(skew=0, FWHM="100 s"),  # <--- skew = 0
        sp.FFT(),
    ]
)

# Create some example CSDM object
test_data = np.zeros(500)
test_data[250] = 100
csdm_object = cp.CSDM(
    dependent_variables=[cp.as_dependent_variable(test_data)],
    dimensions=[cp.LinearDimension(count=500, increment='1 s')]
)

# Apply the processor object
processed_data = processor.apply_operations(data=csdm_object)

gives the following error

TypeError                                 Traceback (most recent call last)
/var/folders/rx/hp_ntm7x7vxfstm8twywpgdw0000gn/T/ipykernel_25161/755687663.py in <module>
----> 1 processed_data = processor.apply_operations(data=csdm_object)
      2 processed_data.real.y[0].components

~/Documents/Python/mrsimulator/src/mrsimulator/signal_processing/__init__.py in apply_operations(self, data, **kwargs)
     79             raise ValueError("The data must be a CSDM object.")
     80         for filters in self.operations:
---> 81             data = filters.operate(data)
     82         self.processed_data = data
     83 

~/Documents/Python/mrsimulator/src/mrsimulator/signal_processing/apodization.py in operate(self, data)
     42         for i in dim_index:
     43             x = self.get_coordinates(dims[i])  # dims[i].coordinates
---> 44             apodization_vector = _get_broadcast_shape(self.fn(x), i, ndim)
     45 
     46             dv_indexes = self._get_dv_indexes(self.dv_index, n=len(data.y))

~/Documents/Python/mrsimulator/src/mrsimulator/signal_processing/utils.py in _get_broadcast_shape(array, dim, ndim)
     17     for dim_ in dim:
     18         none[-dim_ - 1] = slice(None, None, None)
---> 19     return array[tuple(none)]
     20 
     21 

TypeError: 'float' object is not subscriptable

Expected behavior

The data is processed without error

Desktop (please complete the following information):

  • OS: macOS (intel)
  • OpenBLAS
  • Python version: 3.9.3
  • mrsimulator version: 0.7.0dev1

Additional context

A SkewedGaussian with skew =/= 0 can be applied without error

Utility function `generate_site_objects()` to generate a list of Site objects from a list/NumPy array of Site attributes

Utility function, generate_site_objects() to generate a list of Site objects from a list/NumPy array of Site attributes. For example,

isotopes = ['1H', '1H', '1H', '13C', '13C', '23Na']
isotropic_chemical_shifts = [0, 0, 0, 128, 143, 12]
quadrupolar_Cq = [None, None, None, None, None, 5e6]
quadrupolar_eta = [None, None, None, None, None, 0.4]

list_of_sites = generate_site_objects(
    isotopes=isotopes, 
    isotropic_chemical_shifts=isotropic_chemical_shifts,
    quadrupolar={'Cq': quadrupolar_Cq, 'eta': quadrupolar_eta}
)

will generate a list of site objects, where

>>> list_of_sites[0] == Site(isotope='1H', isotropic_chemical_shifts=0)
True

>>> list_of_sites[4] == Site(isotope='13C', isotropic_chemical_shifts= 143)
True

>>> list_of_sites[5] == Site(isotope='23Na', isotropic_chemical_shifts=12, quadrupolar={'Cq': 5e6, 'eta': 0.4})
True

JEOL file format support

JEOL file format support is not available in nmrglue. We have C code for performing the input, but it would not be a straightforward conversion to Python.

Distinguish overlapping class names in the signal_processor module

Some of the operations available throughout the signal processor module have duplicate names but different inheritance patterns/uses. For example:

  • mrsimulator.signal_processor.Scale inherits from class Operation and scales all dependent variable values in a CSDM object by a constant.
  • mrsimulator.signal_processor.affine.Scale inherits from class AffineTransformation and scales the coordinates of a CSDM dimension by a constant.

These two classes perform distinct and useful functions, but share the same name which will cause confusion. Class names, descriptions, and documentation should be updated to remove any ambiguity before version 0.8 is released.

Additionally, the ComplexConjugate class should be implemented for convenience sake.

CSDM origin offset and reference issue

Equations

The CSDM LinearDimension defines coordinates as
coordinates = $\Delta x(J_k - Z_k) + b_k$,
where $J_k = [0, 1, ... N_k -1]$. When complex_fft=False, $Z_k$ = 0. When complex fft=True, $Z_k = N_k/2$ for even $N_k$ else $(N_k-1)/2$

  • coordinates_offset = $b_k$
  • increment = $\Delta x_k$
  • count = N

For NMR datasets, here are two cases---when origin_offset is defined at the receiver frequency, and origin_offset is defined at the reference frequency.

origin_offset $= w_\text{RF}$ origin_offset $= w_\text{ref}$
complex_fft = True $w_\text{ref} = w_\text{RF} - b$ $w_\text{RF} = w_\text{ref} + b$
complex_fft = False, $N$ is odd $w_\text{ref} = w_\text{RF} - (b + \frac{N-1}{2} \Delta x)$ $w_\text{RF} = w_\text{ref} + (b + \frac{N-1}{2} \Delta x)$
complex_fft = False, $N$ is even, $\Delta x$ > 0 $w_\text{ref} = w_\text{RF} - (b + \frac{N}{2} \Delta x)$ $w_\text{RF} = w_\text{ref} + (b + \frac{N}{2} \Delta x)$
complex_fft = False, $N$ is even, $\Delta x$ < 0 $w_\text{ref} = w_\text{RF} - (b + (\frac{N}{2} - 1) \Delta x)$ $w_\text{RF} = w_\text{ref} + (b + (\frac{N}{2} - 1) \Delta x)$

The conversion from Hz -> ppm is coordinates / ${w_\text{ref}}$. The difference is that when origin_offset is ${w_\text{RF}}$, the value of ${w_\text{ref}}$ depends on how the LinearDimension is defined.


What happens to the origin offset for a data subset?

  • If the origin offset is $w_\text{ref}$, we retain both frequency and ppm dimension scale for the subset data but lose the information on $w_\text{RF}$. However, does $w_\text{RF}$ has meaning for a data subset?

  • If the origin offset is $w_\text{RF}$, we lose the information on $w_\text{ref}$. Therefore, the subset data can only be represented in frequency dimension, not dimensionless ppm scale. We retain $w_\text{RF}$, which again seems meaning less for a data subset.


Cases

1 When dataset is the full spectrum

property origin_offset $= w_\text{ref}$ origin_offset $= w_\text{RF}$
always known $w_\text{ref}$ $w_\text{RF}$
can be derived $w_\text{RF}$ $w_\text{ref}$
information loss - -
absolute_coordinates
coordinates
ppm_scale (using above equations)

2 Subset of the full spectrum (keeping the origin_offset the same as the original dataset)

property origin_offset $= w_\text{ref}$ origin_offset $= w_\text{RF}$
always known $w_\text{ref}$ $w_\text{RF}$
can be derived - -
information loss $w_\text{RF}$ $w_\text{ref}$
absolute_coordinates
coordinates
ppm_scale (using above equations)

3 Subset of the full spectrum (updating the origin_offset to maintain the same ppm scale)

property origin_offset $= w_\text{ref}$ origin_offset $= w'_\text{RF}$
always known $w_\text{ref}$ $w'_\text{RF}$
can be derived - -
information loss $w_\text{RF}$ $w_\text{RF}$
absolute_coordinates
coordinates
ppm_scale (using above equations)

Scenarios

  • When origin_offset is $w_\text{RF}$. Case 1 and Case 2(subset has the same origin_offset as the original)
    original-1
    subset-1

Test file scenario-1.zip
Summary origin_offset is always $w_\text{RF}$. The coordinates in Hz are known. Since there is no evidence if the csdm object is a complete or a subset, $w_\text{ref}$ and therefore the coordinates in ppm are presumed incorrect.

  • When origin_offset is $w_\text{ref}$. Case 1 and Case 2(subset has the same origin_offset as the original)
    original-2
    subset-2

Test file scenario-2.zip
Summary origin_offset is always $w_\text{ref}$. The coordinates in Hz and ppm are always known. Since there is no evidence if the csdm object is a complete or a subset, the $w_\text{RF}$ is presumed incorrect.

Include a new `set_state` attribute to `sim.config`

All calculations in mrsimulator assume solid-state NMR spectrum simulation averaging over thoughts of orientations over multiple sidebands. For liquid state NMR simulation, only isotropic contributions are relevant, and therefore, computing frequencies over multiple orientations and sidebands is not optimum.

Proposed solution
Add a new sim.config.set_state attribute, an enumeration with two literals [solid, liquid]

  • When sim.config.set_state="solid" (default), the code is as is.

  • When sim.config.set_state="liquid", the following changes must be forces.

sim.config.integration_density=1,
sim.config.integration_volume="octant",
sim.config.number_of_sidebands=1,
sim.config.number_of_gamma_angles=1

The default freq_contrib for liquids is ["Shielding1_0", "J1_0"]

Simplify the `freq_contrib` attribute

freq_contrib is an event attribute that holds a list of enumeration literals, each designating a given order and rank frequency contribution, e.g., shielding1_0 is the 0th rank nuclear shielding frequency contribution from a 1st order perturbation expansion of the nuclear shielding Hamiltonian. The freq_contrib list is long, and new enumerations representing a sublist of freq_contrib literal might be useful.

Proposed new literals Expands to freq_contrib sublist
Shielding Shielding1_0, Shielding1_2
Quad Quad1_2, Quad2_0, Quad2_2, Quad2_4
J J1_0, J1_2
D D1_2

Simplifying transition pathways by adding weights pathways which are the same except where p=0

For a list of pathways which include symmetries of p=0, the given transition pathways might only differ by the p=0 transition. In that case, pathways with the same transition (except for the p=0) can have their weights added to create a list of simplified pathways. For example, the following 6 transition pathways could be simplified down to 2 transition pathways

[|-1.0⟩⟨1.0| ⟶ |-1.0⟩⟨-1.0| ⟶ |0.0⟩⟨-1.0|, weight=(1+0j),
 |-1.0⟩⟨1.0| ⟶ |-1.0⟩⟨-1.0| ⟶ |1.0⟩⟨0.0|, weight=(1+0j),
 |-1.0⟩⟨1.0| ⟶ |0.0⟩⟨0.0| ⟶ |0.0⟩⟨-1.0|, weight=(1+0j),
 |-1.0⟩⟨1.0| ⟶ |0.0⟩⟨0.0| ⟶ |1.0⟩⟨0.0|, weight=(1+0j),
 |-1.0⟩⟨1.0| ⟶ |1.0⟩⟨1.0| ⟶ |0.0⟩⟨-1.0|, weight=(1+0j),
 |-1.0⟩⟨1.0| ⟶ |1.0⟩⟨1.0| ⟶ |1.0⟩⟨0.0|, weight=(1+0j)]

equivalent to

[|-1.0⟩⟨1.0| ⟶ |0.0⟩⟨-1.0|, weight=(1+0j),
 |-1.0⟩⟨1.0| ⟶ |1.0⟩⟨0.0|, weight=(1+0j)]

The weights here would sum to 3, but that is because TotalMixing causes all weights to go to 1. More discussion on how to handle certain cases is warranted.

Add more operations to the post-simulation `SignalProcessor` class.

Module apodization

  • WindowFunction apodization, that is, sinc wiggle artifacts.
  • Mask(array:np.ndarray, dv_index: tuple, dim_index: tuple). Mask the data by multiplying the NumPy array to the CSDM dependent variable object at index dv_index and along the dim_index dimension.

Module convolution

  • SkewGaussian convolution.

Module base

  • Linear function scales the simulation amplitude and then adds an offset.

Module baseline

  • baseline.ConstantOffset(offset: float): Add an offset to the simulation.
  • baseline.Polynomial(x0: float, x1: float, x2: float, x3: float): Add a polinomial \sum_i(x_i * x^i)

Add documentation for each function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.