Skip to content

Commit

Permalink
defer some expensive imports
Browse files Browse the repository at this point in the history
  • Loading branch information
atmorling committed May 17, 2024
1 parent 86a47b2 commit 2d1bed5
Show file tree
Hide file tree
Showing 6 changed files with 21 additions and 18 deletions.
4 changes: 2 additions & 2 deletions ecoscope/analysis/ecograph.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import numpy as np
import pandas as pd
import rasterio
import sklearn.base
from affine import Affine
from shapely.geometry import shape
from skimage.draw import line
Expand Down Expand Up @@ -119,6 +118,7 @@ def to_geotiff(self, feature, output_path, individual="all", interpolation=None,
transform : sklearn.base.TransformerMixin or None
A feature transform method (Default : None)
"""
from sklearn.base import TransformerMixin

if feature in self.features:
if individual == "all":
Expand All @@ -130,7 +130,7 @@ def to_geotiff(self, feature, output_path, individual="all", interpolation=None,
else:
raise ValueError("This feature was not computed by EcoGraph")

if isinstance(transform, sklearn.base.TransformerMixin):
if isinstance(transform, TransformerMixin):
nan_mask = ~np.isnan(feature_ndarray)
feature_ndarray[nan_mask] = transform.fit_transform(feature_ndarray[nan_mask].reshape(-1, 1)).reshape(
feature_ndarray[nan_mask].shape
Expand Down
5 changes: 3 additions & 2 deletions ecoscope/analysis/seasons.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import numpy as np
import pandas
import shapely
import sklearn.mixture
from scipy.stats import norm
from sklearn.preprocessing import LabelEncoder

Expand Down Expand Up @@ -50,7 +49,9 @@ def std_ndvi_vals(aoi=None, img_coll=None, nir_band=None, red_band=None, img_sca


def val_cuts(vals, num_seasons=2):
distr = sklearn.mixture.GaussianMixture(n_components=num_seasons, max_iter=500)
from sklearn.mixture import GaussianMixture

distr = GaussianMixture(n_components=num_seasons, max_iter=500)
vals = vals["NDVI"].to_numpy().reshape(-1, 1)
distr.fit(vals)
mu_vars = np.array(
Expand Down
23 changes: 12 additions & 11 deletions ecoscope/analysis/speed.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import typing

import geopandas as gpd
import mapclassify
import pandas as pd
import shapely

Expand Down Expand Up @@ -65,12 +64,23 @@ def apply_classification(x, k, cls_method="natural_breaks", multiples=[-2, -1, 1
The multiples of the standard deviation to add/subtract from the sample mean to define the bins. defaults=
"""

from mapclassify import classifiers

classification_methods = {
"equal_interval": classifiers.EqualInterval,
"natural_breaks": classifiers.NaturalBreaks,
"quantile": classifiers.Quantiles,
"std_mean": classifiers.StdMean,
"max_breaks": classifiers.MaximumBreaks,
"fisher_jenks": classifiers.FisherJenks,
}

classifier = classification_methods.get(cls_method)
if not classifier:
return

map_classifier = classifier(x, multiples) if cls_method == "std_mean" else classifier(x, k)
edges, _, _ = mapclassify.classifiers._format_intervals(map_classifier, fmt="{:.2f}")
edges, _, _ = classifiers._format_intervals(map_classifier, fmt="{:.2f}")
return [float(i) for i in edges]


Expand All @@ -82,12 +92,3 @@ def apply_classification(x, k, cls_method="natural_breaks", multiples=[-2, -1, 1
"#fc8d59",
"#d73027",
]

classification_methods = {
"equal_interval": mapclassify.EqualInterval,
"natural_breaks": mapclassify.NaturalBreaks,
"quantile": mapclassify.Quantiles,
"std_mean": mapclassify.StdMean,
"max_breaks": mapclassify.MaximumBreaks,
"fisher_jenks": mapclassify.FisherJenks,
}
2 changes: 1 addition & 1 deletion ecoscope/base/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import warnings

import astroplan
import astropy
import geopandas as gpd
import numpy as np
Expand Down Expand Up @@ -394,6 +393,7 @@ def get_daynight_ratio(self, n_grid_points=150) -> pd.Series:
pd.Series:
Daynight ratio for each unique individual subject in the grouby_col column.
"""
import astroplan

locations = to_EarthLocation(self.geometry.to_crs(crs=self.estimate_utm_crs()).centroid)

Expand Down
2 changes: 1 addition & 1 deletion ecoscope/mapping/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import matplotlib as mpl
import numpy as np
import pandas as pd
import datashader as ds
import rasterio
import selenium.webdriver
from branca.colormap import StepColormap
Expand Down Expand Up @@ -509,6 +508,7 @@ def add_datashader_gdf(
kwargs
Additional kwargs passed to datashader.transfer_functions.shade
"""
import datashader as ds

gdf = gdf.to_crs(epsg=4326)
bounds = gdf.geometry.total_bounds
Expand Down
3 changes: 2 additions & 1 deletion ecoscope/plotting/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import plotly.graph_objs as go
import shapely
from plotly.subplots import make_subplots
from sklearn.neighbors import KernelDensity


class EcoPlotData:
Expand Down Expand Up @@ -243,6 +242,8 @@ def speed(trajectory):


def plot_seasonal_dist(ndvi_vals, cuts, bandwidth=0.05, output_file=None):
from sklearn.neighbors import KernelDensity

x = ndvi_vals.sort_values().to_numpy().reshape(-1, 1)
kde = KernelDensity(kernel="gaussian", bandwidth=bandwidth).fit(x)
dens = np.exp(kde.score_samples(x))
Expand Down

0 comments on commit 2d1bed5

Please sign in to comment.