Commit ffaaa5b8 authored by benvial's avatar benvial
Browse files

Initial commit

parents
This diff is collapsed.
SHELL := /bin/bash
.PHONY: clean lint req doc test
#################################################################################
# GLOBALS #
#################################################################################
PROJECT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
PROJECT_NAME = refidx
PYTHON_INTERPRETER = python3
HOSTING = gitlab
VERSION=$(shell python3 -c "import refidx; print(refidx.__version__)")
ifeq (,$(shell which conda))
HAS_CONDA=False
else
HAS_CONDA=True
endif
#################################################################################
# COMMANDS #
#################################################################################
default:
@echo "\"make save\"?"
## Set up python interpreter environment
env:
ifeq (True,$(HAS_CONDA))
@echo -e ">>> Detected conda, creating conda environment."
ifeq (3,$(findstring 3,$(PYTHON_INTERPRETER)))
conda create --name $(PROJECT_NAME) python=3
else
conda create --name $(PROJECT_NAME) python=2.7
endif
@echo -e ">>> New conda env created. Activate with:\nsource activate $(PROJECT_NAME)"
else
$(PYTHON_INTERPRETER) -m pip install -q virtualenv virtualenvwrapper
@echo -e ">>> Installing virtualenvwrapper if not already intalled.\nMake sure the following lines are in shell startup file\n\
export WORKON_HOME=$$HOME/.virtualenvs\nexport PROJECT_HOME=$$HOME/Devel\nsource /usr/local/bin/virtualenvwrapper.sh\n"
@bash -c "source `which virtualenvwrapper.sh`;mkvirtualenv $(PROJECT_NAME) --python=$(PYTHON_INTERPRETER)"
@echo -e ">>> New virtualenv created. Activate with:\nworkon $(PROJECT_NAME)"
endif
## Test python environment is setup correctly
testenv:
source activate $(PROJECT_NAME); \
$(PYTHON_INTERPRETER) .ci/testenv.py
## Install Python dependencies
req: testenv
source activate $(PROJECT_NAME)
# $(PYTHON_INTERPRETER) -m pip install -r requirements.txt
.ci/installreq requirements.txt
$(PYTHON_INTERPRETER) -m pip install -e.
## Install Python dependencies for dev and test
dev:
$(PYTHON_INTERPRETER) -m pip install -r test/requirements-dev.txt
install: dev
pip install -e .
## Delete generated files
clean:
@find . | grep -E "(*.pvd*.xdmf|*.msh|*.pvtu|*.vtu|*.pvd|jitfailure*|tmp|__pycache__|\.pyc|\.pyo$\)" | xargs rm -rf
@rm -rf .pytest_cache $(PROJECT_NAME).egg-info/ build/ dist/ tmp/ htmlcov/
cd doc && make clean-all
rm -rf .coverage htmlcov coverage.xml
## Lint using flake8
lint:
flake8 --exit-zero setup.py $(PROJECT_NAME)/ test/*.py examples/
## Check for duplicated code
dup:
pylint --exit-zero -f colorized --disable=all --enable=similarities $(PROJECT_NAME)
## Check for missing docstring
dcstr:
pydocstyle ./$(PROJECT_NAME) || true
## Metric for complexity
rad:
radon cc ./$(PROJECT_NAME) -a -nb
## Run all code checks
lint-all: lint dup dcstr rad
## Reformat code
style:
@echo "Styling..."
isort .
black .
## Push to gitlab
gl:
@echo "Pushing to gitlab..."
git add -A
@read -p "Enter commit message: " MSG; \
git commit -a -m "$$MSG"
git push origin main
## Clean, reformat and push to gitlab
save: clean style gl
## Install requirements for building doc
doc-req:
cd doc && pip install -r requirements.txt
## Build html doc
doc:
cd doc && make dochtml
#
#
# ## Build html doc (without examples)
# doc-noplot:
# cd doc && make clean && make html-noplot && make postpro-html
## Open html doc in a browser
show-doc:
firefox doc/_build/html/index.html
## Run the test suite
test:
rm -rf .coverage htmlcov
pytest ./test --cov=./src/$(PROJECT_NAME) --cov-report term --cov-report html --cov-report xml
## Create a release
release:
$(call message,${@})
@if [ "$(shell git rev-parse --abbrev-ref HEAD)" != "master" ]; then exit 1; fi
@gitlab project-release create --project-id $(GITLAB_PROJECT_ID) \
--name "version $(VERSION)" --tag-name "v$(VERSION)" --description "Released version $(VERSION)"
## Make checksum for release
checksum:
$(call message,${@})
@echo v$(VERSION)
$(eval SHA256 := $(shell curl -sL https://gitlab.com/nannos/nannos/-/archive/v$(VERSION)/nannos-v$(VERSION).tar.gz | openssl sha256 | cut -c10-))
@echo $(SHA256)
## Tag and push tags
tag:
# Make sure we're on the main branch
@if [ "$(shell git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
@echo "Tagging v$(VERSION)..."
git tag v$(VERSION)
git push --tags
## Create python package
package:
$(call message,${@})
@if [ "$(shell git rev-parse --abbrev-ref HEAD)" != "master" ]; then exit 1; fi
@rm -f dist/*
@python3 -m build --sdist --wheel .
## Upload to pypi
pypi: package
$(call message,${@})
@twine upload dist/*
## Tag and upload to pipy
publish: tag pipy
## Download database
dldb:
@git clone https://github.com/polyanskiy/refractiveindex.info-database.git
@cd refractiveindex.info-database && mv LICENSE database && cd ..
@mv refractiveindex.info-database/database src/refidx/
@rm -rf refractiveindex.info-database
###############
#################################################################################
# Self Documenting Commands #
#################################################################################
.DEFAULT_GOAL := help
# Inspired by <http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html>
# sed script explained:
# /^##/:
# * save line in hold space
# * purge line
# * Loop:
# * append newline + line to hold space
# * go to next line
# * if line starts with doc comment, strip comment character off and loop
# * remove target prerequisites
# * append hold space (+ newline) to line
# * replace newline plus comments by `---`
# * print line
# Separate expressions are necessary because labels cannot be delimited by
# semicolon; see <http://stackoverflow.com/a/11799865/1968>
.PHONY: help
help:
@echo -e "$$(tput bold)Available rules:$$(tput sgr0)"
@echo -e
@sed -n -e "/^## / { \
h; \
s/.*//; \
:doc" \
-e "H; \
n; \
s/^## //; \
t doc" \
-e "s/:.*//; \
G; \
s/\\n## /---/; \
s/\\n/ /g; \
p; \
}" ${MAKEFILE_LIST} \
| LC_ALL='C' sort --ignore-case \
| awk -F '---' \
-v ncol=$$(tput cols) \
-v indent=19 \
-v col_on="$$(tput setaf 6)" \
-v col_off="$$(tput sgr0)" \
'{ \
printf "%s%*s%s ", col_on, -indent, $$1, col_off; \
n = split($$2, words, " "); \
line_length = ncol - indent; \
for (i = 1; i <= n; i++) { \
line_length -= length(words[i]) + 1; \
if (line_length <= 0) { \
line_length = ncol - indent - length(words[i]) - 1; \
printf "\n%*s ", -indent, " "; \
} \
printf "%s ", words[i]; \
} \
printf "\n"; \
}' \
| more $(shell test $(shell uname) = Darwin && echo '--no-init --raw-control-chars')
# refidx
Retrieve the refractive index of a material at a given wavelength
from the [refractiveindex.info](https://refractiveindex.info/) database.
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
autodoc:
rm -rf source
sphinx-apidoc -o source/ ../src/refidx
clean-all: clean
rm -rf auto_examples/
rm -rf source
dochtml: autodoc html
$(MAKE) html
# Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: e229421897929cb07cbf685b9fd5447e
tags: 645f666f9bcd5a90fca523b33c5a78b7
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Benjamin Vial
# License: MIT
"""
Refractive index
================
Plot material properties.
"""
import matplotlib.pyplot as plt
import numpy as np
import random
import refidx as ri
import os
plt.style.use("../doc/refidx.mplstyle")
###############################################################################
# Get random material
mat = ri.random()
wr = mat.wavelength_range
Nwl = 100
if wr is not None:
lamb = np.linspace(*wr, Nwl)
else:
lamb = np.linspace(0.4, 1.5, Nwl)
index = mat.get_index(lamb)
print(mat)
print(mat.info)
print("wavelength range: ", wr)
###############################################################################
# Plot index
fig, ax = plt.subplots(2, 1, figsize=(3, 3))
ax[0].plot(lamb, index.real, "-", color="#aa0044")
ax[1].plot(lamb, index.imag, "-", color="#6886b3")
ax[0].set_xlabel(r"Wavelength ($\rm μm$)")
ax[1].set_xlabel(r"Wavelength ($\rm μm$)")
ax[0].set_ylabel(r"$n^{\prime}$")
ax[1].set_ylabel(r"$n^{\prime\prime}$")
plt.suptitle(mat)
plt.tight_layout()
plt.show()
###############################################################################
# Add data reference and comments
html_data = "".join(
[
"<h5>" + k.title() + "</h5>" + "<p>" + v + "</p>"
for k, v in mat.info.items()
if v is not None
]
)
html_data = "<div class=matdata>" + html_data + "</div>"
tmp_dir = os.path.join("..", "doc", "auto_examples")
if os.path.exists(tmp_dir):
# building the docs with sphinx-gallery
with open(os.path.join(tmp_dir, "out.html"), "wt") as fh:
fh.write(html_data)
else:
# running from a terminal or jupyter
from IPython.display import display, HTML
display(HTML(html_data))
####################################
# .. raw:: html
# :file: out.html
%% Cell type:code id: tags:
``` python
%matplotlib inline
```
%% Cell type:markdown id: tags:
\n# Refractive index\n\nPlot material properties.
%% Cell type:code id: tags:
``` python
import matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport refidx as ri\nimport os\n\nplt.style.use("../doc/refidx.mplstyle")
```
%% Cell type:markdown id: tags:
Get random material
%% Cell type:code id: tags:
``` python
mat = ri.random()\n\nwr = mat.wavelength_range\nNwl = 100\nif wr is not None:\n lamb = np.linspace(*wr, Nwl)\nelse:\n lamb = np.linspace(0.4, 1.5, Nwl)\nindex = mat.get_index(lamb)\nprint(mat)\nprint(mat.info)\nprint("wavelength range: ", wr)
```
%% Cell type:markdown id: tags:
Plot index
%% Cell type:code id: tags:
``` python
fig, ax = plt.subplots(2, 1, figsize=(3, 3))\nax[0].plot(lamb, index.real, "-", color="#aa0044")\nax[1].plot(lamb, index.imag, "-", color="#6886b3")\n\nax[0].set_xlabel(r"Wavelength ($\rm μm$)")\nax[1].set_xlabel(r"Wavelength ($\rm μm$)")\nax[0].set_ylabel(r"$n^{\prime}$")\nax[1].set_ylabel(r"$n^{\prime\prime}$")\nplt.suptitle(mat)\nplt.tight_layout()\nplt.show()
```
%% Cell type:markdown id: tags:
Add data reference and comments
%% Cell type:code id: tags:
``` python
html_data = "".join(\n [\n "<h5>" + k.title() + "</h5>" + "<p>" + v + "</p>"\n for k, v in mat.info.items()\n if v is not None\n ]\n)\nhtml_data = "<div class=matdata>" + html_data + "</div>"\n\n\ntmp_dir = os.path.join("..", "doc", "auto_examples")\nif os.path.exists(tmp_dir):\n # building the docs with sphinx-gallery\n with open(os.path.join(tmp_dir, "out.html"), "wt") as fh:\n fh.write(html_data)\nelse:\n # running from a terminal or jupyter\n from IPython.display import display, HTML\n\n display(HTML(html_data))
```
%% Cell type:markdown id: tags:
.. raw:: html\n :file: out.html
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment