Git Product home page Git Product logo

usnistgov / pymcr Goto Github PK

View Code? Open in Web Editor NEW
79.0 5.0 27.0 6.85 MB

pyMCR: Multivariate Curve Resolution for Python

Home Page: https://pages.nist.gov/pyMCR

License: Other

Python 100.00%
unsupervised-learning unsupervised-machine-learning unsupervised-learning-algorithms multivariate spectroscopy hyperspectral hyperspectral-data multivariate-curve-resolution mixture-modeling self-modeling-mixture-analysis

pymcr's Introduction

pytest

Codecov

PyPI - Python Version

PyPI Project Page

Anaconda Cloud

NIST Public Domain

pyMCR: Multivariate Curve Resolution in Python

Documentation available online at https://pages.nist.gov/pyMCR

Software DOI: https://doi.org/10.18434/M32064

Manuscript DOI: https://doi.org/10.6028/jres.124.018

pyMCR is a small package for performing multivariate curve resolution. Currently, it implements a simple alternating regression scheme (MCR-AR). The most common implementation is with ordinary least-squares regression, MCR-ALS.

MCR with non-negativity constraints on both matrices is the same as non-negative matrix factorization (NMF). Historically, other names were used for MCR as well:

  • Self modeling mixture analysis (SMMA)
  • Self modeling curve resolution (SMCR)

Available methods:

  • Regressors:
  • Constraints
    • Non-negativity
    • Normalization
    • Zero end-points
    • Zero (approx) end-points of cumulative summation (can specify nodes as well)
    • Non-negativity of cumulative summation
    • Compress or cut values above or below a threshold value
    • Replace sum-across-features samples (e.g., 0 concentration) with prescribed target
    • Enforce a plane ("planarize"). E.g., a concentration image is a plane.
  • Error metrics / Loss function
    • Mean-squared error
  • Other options
    • Fix known targets (C and/or ST, and let others vary)

What it does do:

  • Approximate the concentration and spectral matrices via minimization routines. This is the core the MCR methods.
  • Enable the application of certain constraints in a user-defined order.

What it does not do:

Dependencies

Note: These are the developmental system specs. Older versions of certain packages may work.

  • python >= 3.4
    • Tested with 3.4.6, 3.5.4, 3.6.3, 3.6.5, 3.7.1
  • numpy (1.9.3)
    • Tested with 1.12.1, 1.13.1, 1.13.3, 1.14.3, 1.14.6
  • scipy (1.0.0)
    • Tested with 1.0.0, 1.0.1, 1.1.0
  • scikit-learn, optional (0.2.0)

Known Issues

Installation

Using pip (hard install)

# Only Python 3.* installed
pip install pyMCR

# If you have both Python 2.* and 3.* you may need
pip3 install pyMCR

Using pip (soft install [can update with git])

# Make new directory for pyMCR and enter it
# Clone from github
git clone https://github.com/usnistgov/pyMCR

# Only Python 3.* installed
pip install -e .

# If you have both Python 2.* and 3.* you may need instead
pip3 install -e .

# To update in the future
git pull

Using setuptools

You will need to download the repository or clone the repository with git:

# Make new directory for pyMCR and enter it
# Clone from github
git clone https://github.com/usnistgov/pyMCR

Perform the install:

python setup.py install

Logging

New in pyMCR 0.4.*, the logging module is now automatically loaded and setup during import (via __init__.py) to print messages. You do not need to do the logger setup below.

New in pyMCR 0.3.1, Python's native logging module is now used to capture messages. Though this is not as convenient as print() statements, it has many advantages.

A simple example that prints simplified logging messages to the stdout (command line):

import sys
import logging

# Need to import pymcr or mcr prior to setting up the logger
from pymcr.mcr import McrAR

logger = logging.getLogger('pymcr')
logger.setLevel(logging.DEBUG)

# StdOut is a "stream"; thus, StreamHandler
stdout_handler = logging.StreamHandler(stream=sys.stdout)

# Set the message format. Simple and removing log level or date info
stdout_format = logging.Formatter('%(message)s')  # Just a basic message akin to print statements
stdout_handler.setFormatter(stdout_format)

logger.addHandler(stdout_handler)

# Begin your code for pyMCR below

Usage

from pymcr.mcr import McrAR
mcrar = McrAR()

# MCR assumes a system of the form: D = CS^T
#
# Data that you will provide (hyperspectral context):
# D [n_pixels, n_frequencies]  # Hyperspectral image unraveled in space (2D)
#
# initial_spectra [n_components, n_frequencies]  ## S^T in the literature
# OR
# initial_conc [n_pixels, n_components]   ## C in the literature

# If you have an initial estimate of the spectra
mcrar.fit(D, ST=initial_spectra)

# Otherwise, if you have an initial estimate of the concentrations
mcrar.fit(D, C=initial_conc)

Example Results

Command line and Jupyter notebook examples are provided in the Examples/ folder. Examples of instantiating the McrAR class with different regressors available in the documentation .

From Examples/Demo.ipynb:

image

image

Citing this Software

If you use pyMCR, citing the following article is much appreciated:

References

LICENSE

This software was developed by employees of the National Institute of Standards and Technology (NIST), an agency of the Federal Government. Pursuant to title 17 United States Code Section 105, works of NIST employees are not subject to copyright protection in the United States and are considered to be in the public domain. Permission to freely use, copy, modify, and distribute this software and its documentation without fee is hereby granted, provided that this notice and disclaimer of warranty appears in all copies.

THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE. IN NO EVENT SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY, CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.

Contact

Charles H Camp Jr: [email protected]

Contributors

pymcr's People

Contributors

ccampjr avatar charlesll avatar ericpre avatar jat255 avatar rkern avatar sshojiro 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

pymcr's Issues

Is matrix augmentation supported

Hello.

Is matrix augmentation supported like in MATLAB MCR-ALS? If not, is there a straightforward way to extend the code to allow row and column augmented matrices?

Thanks.
Amin.

Make more examples

The most illustrative examples are currently in the Demo.ipynb file. I should probably add a few more.

MNT: Stop using ci-helpers in appveyor.yml

To whom it may concern,

If you are using https://github.com/astropy/ci-helpers in your appveyor.yml , please know that the Astropy project has dropped active development/support for Appveyor CI. If it still works, good for you, because we did not remove the relevant files (yet). But if it ever stops working, we have no plans to fix anything for Appveyor CI. Please consider using native Windows support other CI, e.g., Travis CI (see https://docs.travis-ci.com/user/reference/windows/). We apologize for any inconvenience caused.

If this issue is opened in error or irrelevant to you, feel free to close. Thank you.

xref astropy/ci-helpers#464

MCR Fails When All-zero Spectral Channels Present

@CCampJr : @jat255 and I have been testing our Hyperspy MCR implementation. We noticed that if one or more spectral channels in the dataset contains all zeros then MCR returns empty factors. Is this behavior to be expected? If so, is there an accepted way of working around the limitation?

Use of constraints

Hi, is it possible to add a constraint for the MCR ALS method such that the first value of one of the concentration profiles must be equal to 1?

Error with the pyMCR demo

Seems like the demo does not describe correctly how to use the NNLS as it gives the following error

mcrar = McrAR(max_iter=100, st_regr='NNLS', c_regr=OLS(),
c_constraints=[ConstraintNonneg(), ConstraintNorm()])

image

This also fails for the same reason:
mcrar = McrAR(c_regr=NNLS(), st_regr=NNLS(), c_constraints=[], st_constraints=[])

The OLS runs without errors:
mcrar = McrAR(c_regr=OLS(), st_regr=OLS(), c_constraints=[ConstraintNonneg()],
st_constraints=[ConstraintNonneg()])

Could you please provide some clarification or edit the Demo.ipynb and the JRes_NIST_Paper.ipynb accordingly?

Unimodality constraint

Hello,
I would like to use a Unimodality constraint to follow a kinetic process (time-ordered matrix ). Is it possible to perform this kind of study with your package ?

Thank you

Nicolas

Make documentation

Obviously, I need to make documentation. I'll probably start with sphinx and make repo-level docs, but I'm looking into using readthedoc.io. For non-obvious reasons, I cannot use gitpages.

New Features for Version 0.4.X

  • Rank estimation submodule (See PR #21 )

    • SVD
    • HySime
    • SIMPLISMA (?)
  • More examples

  • New Constraints

    • Fix for k iterations
  • Please submit your ideas!

Add "quiet" mode of operation

As @AndrewHerzing and I are working to include pyMCR as a decomposition method into HyperSpy, it would be nice if there was a way to prevent the code from outputting to the stdout on the console.

I would recommend one of two methods:

  1. Rather than print statements, make use of the logging module, so packages that call this library can set the verbosity of the log as needed
  2. Add a quiet parameter throughout the code that when set will prevent outputting to the console (a la most UNIX tools)

Option 1 is more "pythonic", and provides a little more flexibility, so that would be my preferred recommendation.

Error related to missing libifport.so.5 required in scipy.linalg

Hello,

This is an issue related to scipy ( specifically recent versions of intel optimized scipy ). Upon importing pymcr , an error related to missing libifport.so.5 file is encountered.

Build information

# Name                    Version                   Build  Channel
numpy                     1.17.0          py36ha68da19_13    intel
numpy-base                1.17.0                  py36_13    intel
scipy                     1.3.1            py36ha68da19_2    intel

Error observed

>>> import pymcr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ankit/miniconda3/envs/jupy56_new/lib/python3.6/site-packages/pymcr/__init__.py", line 2, in <module>
    from . import mcr
  File "/home/ankit/miniconda3/envs/jupy56_new/lib/python3.6/site-packages/pymcr/mcr.py", line 7, in <module>
    from pymcr.regressors import OLS, NNLS
  File "/home/ankit/miniconda3/envs/jupy56_new/lib/python3.6/site-packages/pymcr/regressors.py", line 14, in <module>
    from scipy.linalg import lstsq as _lstsq
  File "/home/ankit/miniconda3/envs/jupy56_new/lib/python3.6/site-packages/scipy/linalg/__init__.py", line 195, in <module>
    from .misc import *
  File "/home/ankit/miniconda3/envs/jupy56_new/lib/python3.6/site-packages/scipy/linalg/misc.py", line 5, in <module>
    from .blas import get_blas_funcs
  File "/home/ankit/miniconda3/envs/jupy56_new/lib/python3.6/site-packages/scipy/linalg/blas.py", line 214, in <module>
    from scipy.linalg import _fblas
ImportError: libifport.so.5: cannot open shared object file: No such file or directory

Solution
Install specific version of scipy which has been tested with pymcr. From the documentation :

    Python (3.4, 3.5, 3.6, 3.7)
    numpy (1.9.3, 1.11.1, 1.11.3+mkl, 1.14.6, 1.16.2)
    scipy (1.0.0, 1.0.1, 1.1.0)
    sklearn, optional (0.20)
    Sphinx, optional (1.4.5, 1.5.2, 1.6.4, 1.8.4) – only for documentation building

On README.rst and Demo.ipynb

To easily install pyMCR into non-ascii environment (e.g. Windows 10 in Japanese), it would be nice to replace the non-breaking hyphen (U+2011) in line 168 of README.rst into more common hyphen-minus (U+002D) to avoid UnicodeDecordError.

On Demo.ipynb, I guess several mcrals._c_mrd should be mcrals._c_mrd[-1] .

Anyway, this code is what I look for. Thank you so much to share your code!

Test Warning for semilearned

pymcr/tests/test_mcr.py::test_mcr_c_semilearned
C:\Users\chc\Documents\Python\Repos\pyMCR\dist\pyMCR-0.3a0\pymcr\constraints.py:308: RuntimeWarning: invalid value encountered in true_divide
A /= A.sum(axis=self.axis)[:, None]

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.