Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Codeformatting with black #144

Merged
merged 9 commits into from
Mar 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ env:
global:
- TWINE_USERNAME=geostatframework
- CIBW_BEFORE_BUILD="pip install numpy==1.17.3 scipy==1.3.2 cython==0.29.14 setuptools"
- CIBW_TEST_REQUIRES="pytest scikit-learn"
- CIBW_TEST_REQUIRES="pytest scikit-learn gstools"
- CIBW_TEST_COMMAND="pytest -v {project}/tests"

before_install:
Expand All @@ -21,9 +21,9 @@ before_install:
ln -s /c/Python38/python.exe /c/Python38/python3.exe
fi

script:
- python3 -m pip install cibuildwheel==1.3.0
- python3 -m cibuildwheel --output-dir dist
install: python3 -m pip install cibuildwheel==1.3.0

script: python3 -m cibuildwheel --output-dir dist

after_success:
- |
Expand All @@ -40,12 +40,20 @@ notifications:

jobs:
include:
- name: "black check"
services: docker
install: python3 -m pip install black
script: python3 -m black --check pykrige/ examples/ tests/
after_success: echo "all files formatted correctly"
after_failure: echo "some files not formatted correctly"

- name: "sdist and coverage"
services: docker
script:
- python3 -m pip install -U setuptools pytest-cov coveralls scikit-learn
- python3 -m pip install -U numpy==1.17.3 cython==0.29.14
install:
- python3 -m pip install -r requirements_setup.txt
- python3 -m pip install -r requirements_test.txt
- python3 -m pip install -r requirements.txt
script:
- python3 setup.py sdist -d dist
- python3 setup.py build_ext --inplace
- python3 -m pytest --cov pykrige --cov-report term-missing -v tests/
Expand Down
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright (c) 2015-2018, PyKrige Developers
Copyright (c) 2015-2020, PyKrige Developers
All rights reserved.

Redistribution and use in source and binary forms, with or without
Expand Down
15 changes: 5 additions & 10 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import shlex
import sphinx_rtd_theme
import matplotlib

matplotlib.use("Agg")


Expand Down Expand Up @@ -61,9 +62,9 @@
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'restructuredtext',
'.md': 'markdown',
".rst": "restructuredtext",
".txt": "restructuredtext",
".md": "markdown",
}

# The encoding of source files.
Expand Down Expand Up @@ -258,13 +259,7 @@
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
"PyKrige.tex",
"PyKrige Documentation",
"PyKrige developers",
"manual",
)
(master_doc, "PyKrige.tex", "PyKrige Documentation", "PyKrige developers", "manual")
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down
8 changes: 2 additions & 6 deletions docs/source/sphinxext/github_link.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,12 @@ def _linkcode_resolve(domain, info, package, url_fmt, revision):
if not fn:
return

fn = os.path.relpath(
fn, start=os.path.dirname(__import__(package).__file__)
)
fn = os.path.relpath(fn, start=os.path.dirname(__import__(package).__file__))
try:
lineno = inspect.getsourcelines(obj)[1]
except Exception:
lineno = ""
return url_fmt.format(
revision=revision, package=package, path=fn, lineno=lineno
)
return url_fmt.format(revision=revision, package=package, path=fn, lineno=lineno)


def make_linkcode_resolve(package, url_fmt):
Expand Down
26 changes: 14 additions & 12 deletions examples/gstools_covmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,34 @@
import numpy as np
from pykrige.ok import OrdinaryKriging
from matplotlib import pyplot as plt

try:
from gstools import Gaussian

GS_IMP = True
except ImportError:
GS_IMP = False

# conditioning data
data = np.array([[0.3, 1.2, 0.47],
[1.9, 0.6, 0.56],
[1.1, 3.2, 0.74],
[3.3, 4.4, 1.47],
[4.7, 3.8, 1.74]])
data = np.array(
[
[0.3, 1.2, 0.47],
[1.9, 0.6, 0.56],
[1.1, 3.2, 0.74],
[3.3, 4.4, 1.47],
[4.7, 3.8, 1.74],
]
)
# grid definition for output field
gridx = np.arange(0.0, 5.5, 0.1)
gridy = np.arange(0.0, 6.5, 0.1)
# a GSTools based covariance model
if GS_IMP:
cov_model = Gaussian(
dim=2, len_scale=4, anis=.2, angles=-.5, var=.5, nugget=.1
)
cov_model = Gaussian(dim=2, len_scale=4, anis=0.2, angles=-0.5, var=0.5, nugget=0.1)
else:
cov_model = "gaussian"
# ordinary kriging with pykrige
OK1 = OrdinaryKriging(data[:, 0], data[:, 1], data[:, 2], cov_model)
z1, ss1 = OK1.execute('grid', gridx, gridy)
z1, ss1 = OK1.execute("grid", gridx, gridy)
plt.imshow(z1, origin="lower")
if 'CI' not in os.environ:
# skip in continous integration
plt.show()
plt.show()
62 changes: 36 additions & 26 deletions examples/krige_cv.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@

# 2D Kring param opt

param_dict = {"method": ["ordinary", "universal"],
"variogram_model": ["linear", "power", "gaussian", "spherical"],
# "nlags": [4, 6, 8],
# "weight": [True, False]
}
param_dict = {
"method": ["ordinary", "universal"],
"variogram_model": ["linear", "power", "gaussian", "spherical"],
# "nlags": [4, 6, 8],
# "weight": [True, False]
}

estimator = GridSearchCV(Krige(), param_dict, verbose=True)

Expand All @@ -29,23 +30,28 @@
estimator.fit(X=X, y=y)


if hasattr(estimator, 'best_score_'):
print('best_score R² = {:.3f}'.format(estimator.best_score_))
print('best_params = ', estimator.best_params_)
if hasattr(estimator, "best_score_"):
print("best_score R² = {:.3f}".format(estimator.best_score_))
print("best_params = ", estimator.best_params_)

print('\nCV results::')
if hasattr(estimator, 'cv_results_'):
for key in ['mean_test_score', 'mean_train_score',
'param_method', 'param_variogram_model']:
print(' - {} : {}'.format(key, estimator.cv_results_[key]))
print("\nCV results::")
if hasattr(estimator, "cv_results_"):
for key in [
"mean_test_score",
"mean_train_score",
"param_method",
"param_variogram_model",
]:
print(" - {} : {}".format(key, estimator.cv_results_[key]))

# 3D Kring param opt

param_dict3d = {"method": ["ordinary3d", "universal3d"],
"variogram_model": ["linear", "power", "gaussian", "spherical"],
# "nlags": [4, 6, 8],
# "weight": [True, False]
}
param_dict3d = {
"method": ["ordinary3d", "universal3d"],
"variogram_model": ["linear", "power", "gaussian", "spherical"],
# "nlags": [4, 6, 8],
# "weight": [True, False]
}

estimator = GridSearchCV(Krige(), param_dict3d, verbose=True)

Expand All @@ -57,12 +63,16 @@
estimator.fit(X=X3, y=y)


if hasattr(estimator, 'best_score_'):
print('best_score R² = {:.3f}'.format(estimator.best_score_))
print('best_params = ', estimator.best_params_)
if hasattr(estimator, "best_score_"):
print("best_score R² = {:.3f}".format(estimator.best_score_))
print("best_params = ", estimator.best_params_)

print('\nCV results::')
if hasattr(estimator, 'cv_results_'):
for key in ['mean_test_score', 'mean_train_score',
'param_method', 'param_variogram_model']:
print(' - {} : {}'.format(key, estimator.cv_results_[key]))
print("\nCV results::")
if hasattr(estimator, "cv_results_"):
for key in [
"mean_test_score",
"mean_train_score",
"param_method",
"param_variogram_model",
]:
print(" - {} : {}".format(key, estimator.cv_results_[key]))
44 changes: 26 additions & 18 deletions examples/krige_geometric.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,42 +17,50 @@
# of nodes and a uniform distribution of values in the interval
# [2.0, 5.5]:
N = 7
lon = 360.0*np.random.random(N)
lat = 180.0/np.pi*np.arcsin(2*np.random.random(N)-1)
z = 3.5*np.random.rand(N) + 2.0
lon = 360.0 * np.random.random(N)
lat = 180.0 / np.pi * np.arcsin(2 * np.random.random(N) - 1)
z = 3.5 * np.random.rand(N) + 2.0

# Generate a regular grid with 60° longitude and 30° latitude steps:
grid_lon = np.linspace(0.0, 360.0, 7)
grid_lat = np.linspace(-90.0, 90.0, 7)

# Create ordinary kriging object:
OK = OrdinaryKriging(lon, lat, z, variogram_model='linear', verbose=False,
enable_plotting=False, coordinates_type='geographic')
OK = OrdinaryKriging(
lon,
lat,
z,
variogram_model="linear",
verbose=False,
enable_plotting=False,
coordinates_type="geographic",
)

# Execute on grid:
z1, ss1 = OK.execute('grid', grid_lon, grid_lat)
z1, ss1 = OK.execute("grid", grid_lon, grid_lat)

# Create ordinary kriging object ignoring curvature:
OK = OrdinaryKriging(lon, lat, z, variogram_model='linear', verbose=False,
enable_plotting=False)
OK = OrdinaryKriging(
lon, lat, z, variogram_model="linear", verbose=False, enable_plotting=False
)

# Execute on grid:
z2, ss2 = OK.execute('grid', grid_lon, grid_lat)
z2, ss2 = OK.execute("grid", grid_lon, grid_lat)

# Print data at equator (last longitude index will show periodicity):
print("Original data:")
print("Longitude:",lon.astype(int))
print("Latitude: ",lat.astype(int))
print("z: ",np.array_str(z, precision=2))
print("Longitude:", lon.astype(int))
print("Latitude: ", lat.astype(int))
print("z: ", np.array_str(z, precision=2))
print("\nKrige at 60° latitude:\n======================")
print("Longitude:",grid_lon)
print("Value: ",np.array_str(z1[5,:], precision=2))
print("Sigma²: ",np.array_str(ss1[5,:], precision=2))
print("Longitude:", grid_lon)
print("Value: ", np.array_str(z1[5, :], precision=2))
print("Sigma²: ", np.array_str(ss1[5, :], precision=2))
print("\nIgnoring curvature:\n=====================")
print("Value: ",np.array_str(z2[5,:], precision=2))
print("Sigma²: ",np.array_str(ss2[5,:], precision=2))
print("Value: ", np.array_str(z2[5, :], precision=2))
print("Sigma²: ", np.array_str(ss2[5, :], precision=2))

##====================================OUTPUT==================================
# ====================================OUTPUT==================================
# >>> Original data:
# >>> Longitude: [122 166 92 138 86 122 136]
# >>> Latitude: [-46 -36 -25 -73 -25 50 -29]
Expand Down
42 changes: 24 additions & 18 deletions examples/kriging_1D.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@

import numpy as np
import matplotlib.pyplot as plt
from pykrige import OrdinaryKriging

plt.style.use('ggplot')

# Data taken from https://blog.dominodatalab.com/fitting-gaussian-process-models-python/
plt.style.use("ggplot")

X, y = np.array([[-5.01, 1.06], [-4.90, 0.92], [-4.82, 0.35], [-4.69, 0.49], [-4.56, 0.52],
# fmt: off
# Data taken from
# https://blog.dominodatalab.com/fitting-gaussian-process-models-python/
X, y = np.array([
[-5.01, 1.06], [-4.90, 0.92], [-4.82, 0.35], [-4.69, 0.49], [-4.56, 0.52],
[-4.52, 0.12], [-4.39, 0.47], [-4.32,-0.19], [-4.19, 0.08], [-4.11,-0.19],
[-4.00,-0.03], [-3.89,-0.03], [-3.78,-0.05], [-3.67, 0.10], [-3.59, 0.44],
[-3.50, 0.66], [-3.39,-0.12], [-3.28, 0.45], [-3.20, 0.14], [-3.07,-0.28],
Expand All @@ -33,33 +36,36 @@
[3.52 ,-0.55], [3.63 ,-0.92], [3.72 ,-0.76], [3.80 ,-0.41], [3.91 , 0.12],
[4.04 , 0.25], [4.13 , 0.16], [4.24 , 0.26], [4.32 , 0.62], [4.44 , 1.69],
[4.52 , 1.11], [4.65 , 0.36], [4.74 , 0.79], [4.84 , 0.87], [4.93 , 1.01],
[5.02 , 0.55]]).T


from pykrige import OrdinaryKriging
[5.02 , 0.55]
]).T
# fmt: on

X_pred = np.linspace(-6, 6, 200)

# pykrige doesn't support 1D data for now, only 2D or 3D
# adapting the 1D input to 2D
uk = OrdinaryKriging(X, np.zeros(X.shape), y, variogram_model='gaussian',)
uk = OrdinaryKriging(X, np.zeros(X.shape), y, variogram_model="gaussian")

y_pred, y_std = uk.execute('grid', X_pred, np.array([0.]))
y_pred, y_std = uk.execute("grid", X_pred, np.array([0.0]))

y_pred = np.squeeze(y_pred)
y_std = np.squeeze(y_std)

fig, ax = plt.subplots(1, 1, figsize=(10, 4))
ax.scatter(X, y, s=40, label='Input data')
ax.scatter(X, y, s=40, label="Input data")


ax.plot(X_pred, y_pred, label='Predicted values')
ax.fill_between(X_pred, y_pred - 3*y_std, y_pred + 3*y_std, alpha=0.3, label='Confidence interval')
ax.plot(X_pred, y_pred, label="Predicted values")
ax.fill_between(
X_pred,
y_pred - 3 * y_std,
y_pred + 3 * y_std,
alpha=0.3,
label="Confidence interval",
)
ax.legend(loc=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_xlim(-6, 6)
ax.set_ylim(-2.8, 3.5)
if 'CI' not in os.environ:
# skip in continous integration
plt.show()
plt.show()
Loading