AttributeError: 'IcclimLogger' object has no attribute 'timezone' jupyter notebook - python

I have following block of code:
i want to use ICCLIM (Indice Calculation CLIMate) is a Python library
To calculate some indices
how to solve this problem ??
files = ['tasmax_day_CNRM-CM5_historical_r1i1p1_19950101-19991231.nc', 'tasmax_day_CNRM-CM5_historical_r1i1p1_20000101-20041231.nc', 'tasmax_day_CNRM-CM5_historical_r1i1p1_20050101-20051231.nc']
dt1 = datetime.datetime(1998,1,1)
dt2 = datetime.datetime(2005,12,31)
out_f ='SU_JJA_CNRM-CM5_historical_r1i1p1_1998-2005.nc' # OUTPUT FILE: summer season values of SU
icclim.index(index_name='SU', in_files=files, var_name='tasmax', time_range=[dt1, dt2], slice_mode='JJA', out_file=out_f)
dt1 = datetime.datetime(1998,1,1)
dt2 = datetime.datetime(2005,12,31)
out_f = 'SU_JJA_CNRM-CM5_historical_r1i1p1_1998-2005.nc' # OUTPUT FILE: summer season values of SU
icclim.index(index_name='SU', in_files=files, var_name='tasmax', time_range=[dt1, dt2], slice_mode='JJA', out_file=out_f)
and the import list is
import numpy
import cython
import netcdftime
import cftime
import netCDF4
import sys
import glob
import os
import datetime
import dask
from netCDF4 import Dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xarray
import nc_time_axis
import logging
import pytest
import setuptools
import xclim
import icclim
we i run the code the error keep show
here is the error
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2572/579676545.py in <module>
2 dt2 = datetime.datetime(1986,12,31)
3
----> 4 icclim.index(index_name='CD', in_files='C:/Users/Dana/Desktop/icclim/pr_year_1986.nc',time_range=[dt1, dt2], var_name='pr', slice_mode='year', out_file='C:/Users/Dana/Desktop/icclim/new_pr_year_1986.nc')
C:\ProgramData\Anaconda\lib\site-packages\icclim\main.py in index(in_files, var_name, index_name, slice_mode, time_range, out_file, threshold, transfer_limit_Mbytes, callback, callback_percentage_start_value, callback_percentage_total, base_period_time_range, window_width, only_leap_years, ignore_Feb29th, interpolation, out_unit, netcdf_version, user_index, save_percentile, logs_verbosity, indice_name, user_indice)
127 log.set_verbosity(logs_verbosity)
128
--> 129 log.start_message()
130 callback(callback_percentage_start_value)
131 if indice_name is not None:
C:\ProgramData\Anaconda\lib\site-packages\icclim\icclim_logger.py in start_message(self)
62
63 # flake8: noqa
---> 64 time_now = time.asctime(time.gmtime()) + " " + self.timezone
65 if self.verbosity == Verbosity.SILENT:
66 return
AttributeError: 'IcclimLogger' object has no attribute 'timezone'

Sorry for the late reply. This was due to a bug within icclim and it has been fixed in a later version.
I advise you to try the latest version (5.1.0) available on pypi or conda-forge.

Related

Importing a .tif into Jupyter Notebook using python script

I have been trying to import a .tif into python using the following code:
image = 'location/map_Western_Cape.tif' #use same location as above
geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
image_Gauteng = 'location/map_Gauteng.tif' #use same location as above
geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
However, I keep getting this error message:
AttributeError Traceback (most recent call last)
Input In [11], in <cell line: 4>()
1 # Load the .tif from local machine
3 image = 'C:/Users/kiral/OneDrive - Stellenbosch University/BScHons Global Change/Guy/map_Western_Cape.tif' #use same location as above
----> 4 geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
6 image_Gauteng = 'C:/Users/kiral/OneDrive - Stellenbosch University/BScHons Global Change/Guy/map_Gauteng.tif' #use same location as above
7 geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
File ~\anaconda3\lib\site-packages\geemap\common.py:12559, in plot_raster(image, band, cmap, proj, figsize, open_kwargs, **kwargs)
12557 try:
12558 import pvxarray
> 12559 import rioxarray
12560 import xarray
12561 except ImportError:
File ~\anaconda3\lib\site-packages\rioxarray\__init__.py:6, in <module>
3 __author__ = """rioxarray Contributors"""
4 __email__ = "alansnow21#gmail.com"
----> 6 import rioxarray.raster_array # noqa
7 import rioxarray.raster_dataset # noqa
8 from rioxarray._io import open_rasterio # noqa
File ~\anaconda3\lib\site-packages\rioxarray\raster_array.py:28, in <module>
14 from typing import (
15 Any,
16 Dict,
(...)
24 Union,
25 )
27 import numpy as np
---> 28 import rasterio
29 import rasterio.mask
30 import rasterio.warp
File ~\anaconda3\lib\site-packages\rasterio\__init__.py:44, in <module>
41 import warnings
43 import rasterio._loading
---> 44 with rasterio._loading.add_gdal_dll_directories():
45 from rasterio._show_versions import show_versions
46 from rasterio._version import gdal_version, get_geos_version, get_proj_version
AttributeError: partially initialized module 'rasterio' has no attribute '_loading' (most likely due to a circular import)
I have tried installing all of the listed modules, but that ended up getting a bunch of errors too.
Could anyone recommend a way to import these tifs?

exec vs import, why errors only in one of them

I downloaded the code from here https://github.com/SpaceNetChallenge/SpaceNet_SAR_Buildings_Solutions, specifically using model 1. I downloaded the weights corresponding and created the following file to load the model and test. First, I copy the Unet part in main.py into a separate file umodel.py and the test file as follows
import torch
exec(open("./umodel.py").read())
network_data = torch.load('snapshot_fold_8_best')
print(network_data.keys())
import sys
sys.path.append("geffnet")
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
args = Namespace(extra_num = 1,
dec_ch = [32, 64, 128, 256, 1024],
stride=32,
net='b5',
bot1x1=True,
glob=True,
bn=True,
aspp=True,
ocr=True,
aux_scale=True)
def load_state_dict(model, state_dict):
missing_keys = []
# from UnetOS.umodel import Unet
exec(open("./umodel.py").read())
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
# from UnetOS.umodel import *
model = Unet(extra_num = args.extra_num, dec_ch = args.dec_ch, stride=args.stride, net=args.net, bot1x1 = args.bot1x1, glob=args.glob, bn=args.bn, aspp=args.aspp,
ocr=args.ocr, aux = args.aux_scale > 0).cuda()
load_state_dict(model, network_data)
My question is, why exec(open("./umodel.py").read()) works nicely but whenever I tried to import from umodel import Unet it has errors
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10492/1282530406.py in <module>
9 # ah
10 model = Unet(extra_num = args.extra_num, dec_ch = args.dec_ch, stride=args.stride, net=args.net, bot1x1 = args.bot1x1, glob=args.glob, bn=args.bn, aspp=args.aspp,
---> 11 ocr=args.ocr, aux = args.aux_scale > 0).cuda()
12 #model = Unet()
13 #print(network_data.key())
D:\hines\Pretrained\1-zbigniewwojna\UnetOS\umodel.py in __init__(self, extra_num, dec_ch, stride, net, bot1x1, glob, bn, aspp, ocr, aux)
238 ['ir_r4_k5_s2_e6_c192_se0.25'],
239 ['ir_r1_k3_s1_e6_c320_se0.25']]
--> 240 enc = GenEfficientNet(in_chans=3, block_args=decode_arch_def(arch_def, depth_multiplier),
241 num_features=round_channels(1280, channel_multiplier, 8, None), stem_size=32,
242 channel_multiplier=channel_multiplier, act_layer=resolve_act_layer({}, 'swish'),
NameError: name 'decode_arch_def' is not defined
The main file is as follow https://github.com/SpaceNetChallenge/SpaceNet_SAR_Buildings_Solutions/blob/master/1-zbigniewwojna/main.py
From the error message, it appears that decode_arch_def is not available and looking at your imports, that has to come from from geffnet.efficientnet_builder import * (it does https://github.com/rwightman/gen-efficientnet-pytorch/blob/master/geffnet/efficientnet_builder.py)
Your exec must have worked because it followed a similar import, that brought decode_arch_def in scope - exec() executes code in the current scope, so it will work because in that scope decode_arch_def is already defined.
However, when you import, the imported module itself doesn't have the function you need in scope. You should add the required import statements to the file you're importing to bring them into scope and it should work.
For example, with a mod.py containing this:
def my_func():
print(datetime.now())
This works:
from datetime import datetime
exec(open("./mod.py").read())
my_func()
But this does not:
from datetime import datetime
import mod
mod.my_func()
To make that work, mod.py would have to be:
from datetime import datetime
def my_func():
print(datetime.now())
And the import of datetime wouldn't be needed in the main program, since it's not referenced there. Your code has a similar issue - you need to determine all the dependencies of your Unet class and import them.

Requests not defined after importing from a file

I have imported a file image_function.py to my notebook. However when i tried using one of the functions im_reverse, it gave me an error.
Code:
import image_function
image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-61-afc744ac8a12> in <module>()
1 import image_function
----> 2 image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
/content/image_function.py in im_reverse(image_path, reverse, url)
45 mat_image_column_reverse[c][i] = mat_image_reverse[j][i]
46 c += 1
---> 47
48 plt.axis('off')
49
NameError: name 'requests' is not defined
The error happened before it reached the code for reversing vertically, which is down below.
What's inside image_function:
#libraries:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import imshow
from PIL import Image
import copy
import requests
from io import BytesIO
This is the code after the error:
def im_reverse(image_path, reverse = 'horizontal', url = True):
if url == True:
response = requests.get(image_path)
with Image.open(BytesIO(response.content)) as image:
mat_image = np.array(image, dtype=int)
m, n, depth = mat_image.shape
if reverse == 'horizontal':
mat_image_reverse = copy.deepcopy(mat_image)
mat_image_rows_reverse = copy.deepcopy(mat_image)
for i in range(m):
c = 0
for j in range(n-1,-1,-1):
mat_image_rows_reverse[i][c] = mat_image_reverse[i][j]
c += 1
plt.axis('off')
return imshow(mat_image_rows_reverse)
I have tried a lot of solutions on the web. However i dont see anything wrong. I have also tried a deliberate from requests import get or !pip install requests and it still didn't work.
Can anyone please offer a solution. Thanks
It sounds like you need to install requests:
python3 -m pip install requests

how to correctly get R sessionInfo() from python script with rpy2 api?

I am trying to get R sessioninfo() by using rpy2 in python script, the reason because I am going to make api call from python to custom R library. The basic thing I want to try is get current R sessioninfo() using simple python script.
my attempt:
here is the attempt that I tried by following this SO post:
import rpy2.robjects as robjects
import os
os.environ['R_HOME'] = "C:/PROGRA~1/R/R-36~1.3"
robjects.r('''
source('myfunc.r')
''')
myfunc = function(){
return(sessionInfo())
}
I got R_HOME by using Sys.getenv('R_HOME') or R.home() in R studio.
new updated attempt:
based on #Parfait suggestion, I aso tried this way:
pip install .\rpy2-2.9.5-cp37-cp37m-win_amd64.whl
import os
os.environ['PYTHONHOME'] = r"C:\Users\mia\AppData\Local\Programs\Python\Python37"
os.environ['PYTHONPATH'] = r'C:\Users\mia\AppData\Local\Programs\Python\Python37\Lib\site-packages'
os.environ['R_HOME'] = r'C:\Program Files\R\R-3.6.3'
os.environ['R_USER'] = r'C:\Users\mia\AppData\Local\Programs\Python\Python37\Lib\site-packages\rpy2'
# importing rpy2
import rpy2
import rpy2.robjects as robjects
# test : evaluating R code
robjects.r('''
# create a function `f`
f <- function(r, verbose=FALSE) {
if (verbose) {
cat("I am calling f().\n")
}
2 * pi * r
}
''')
r_f = robjects.r['f']
res = r_f(3)
print(res[0])
but now I get another error:
> ---------------------------------------------------------------
> OSError Traceback (most recent call last)
> <ipython-input-27-b5597ba1add5> in <module>
> 1 import rpy2
> ----> 2 import rpy2.robjects as robjects
> 3 import itertools
> 4 from datetime import datetime
> 5 import rpy2.rinterface as rinterface
>
> c:\users\mia\appdata\local\programs\python\python37\lib\site-packages\rpy2\robjects\__init__.py
> in <module>
> 14 import itertools
> 15 from datetime import datetime
> ---> 16 import rpy2.rinterface as rinterface
> 17 import rpy2.rlike.container as rlc
> 18
>
> c:\users\mia\appdata\local\programs\python\python37\lib\site-packages\rpy2\rinterface\__init__.py
> in <module>
> 44
> 45 if sys.platform == 'win32':
> ---> 46 _load_r_dll(R_HOME)
> 47
> 48 # cleanup the namespace
>
> c:\users\mia\appdata\local\programs\python\python37\lib\site-packages\rpy2\rinterface\__init__.py
> in _load_r_dll(r_home)
> 28 if r_bin not in os.environ.get('PATH'):
> 29 os.environ['PATH'] = ';'.join((os.environ.get('PATH'), r_bin, r_mod))
> ---> 30 ctypes.CDLL(r_dll)
> 31
> 32 R_HOME = get_r_home()
>
> c:\users\mia\appdata\local\programs\python\python37\lib\ctypes\__init__.py
> in __init__(self, name, mode, handle, use_errno, use_last_error)
> 362
> 363 if handle is None:
> --> 364 self._handle = _dlopen(self._name, mode)
> 365 else:
> 366 self._handle = handle
>
> OSError: [WinError 126] The specified module could not be found
now I can import rpy2 also can import rpy2.robjects, but can't able to get R sessionInfo() correctly. any further thoughts? thanks
desired output:
I just want to print out R sessionInfo() in jupyternotebook or python script by using rpy2? any solution to make this happen? any thoughts? thanks a lot
I ran into same problem on my windows machine, you are having this problem because you didn't add R installed path to system variables. You should do the following:
open Control Panel\System and Security\System, open Environment Variables, find System Variables, then select Path to add C:\Program Files\R\R-3.3.2\bin\x64 to your System Variables. Make sure you install rpy2 from uci website, download rpy2.whl then pip install rpy2.xx.xx.whl
Then do this setting in your python script:
import os
os.environ['PYTHONHOME'] = r"C:\Users\me\AppData\Local\Programs\Python\Python37"
os.environ['PYTHONPATH'] = r"C:\Users\me\AppData\Local\Programs\Python\Python37\Lib\site-packages"
os.environ['R_HOME'] = r"C:\Program Files\R\R-3.3.2"
os.environ['R_USER'] = r"C:\Users\me\AppData\Local\Programs\Python\Python37\Lib\site-packages\rpy2"
import rpy2
import rpy2.robjects as robjects
pi = robjects.r['pi']
print(pi)
this problem can solve your issue right away.

Python: AttributeError

When I run my script I get this error:
File "test_cm.py", line 34, in
labels = labels_img.get_data() AttributeError: 'tuple' object has no attribute 'get_data'
from dipy.tracking.eudx import EuDX
from dipy.reconst import peaks, shm
from dipy.tracking import utils
from dipy.data import read_stanford_labels
from dipy.io.gradients import read_bvals_bvecs
import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
source="prova11/"
path=source
print('loading data')
bvals,bvecs=read_bvals_bvecs(source+"bvals",source+"bvecs")
bvals[bvals < 10] = 0
img = nib.load(source+"segment-TO-b0.nii")
data = img.get_data()
affine=img.affine
labels_img = read_stanford_labels()
labels = labels_img.get_data()
read_stanford_labels() returns a tuple, and tuples don't have a get_data() method which is why the error says AttributeError: 'tuple' object has no attribute 'get_data'.
You should go over your read_stanford_labels function and see why it returns a tuple, which isn't what you expected.
Edit: By going over the documentation/example your code should be
hardi_img, gtab, labels_img = read_stanford_labels() instead of
labels_img = read_stanford_labels().
Alternatively, if you don't need the first 2 values, you can use
labels_img = read_stanford_labels()[-1] or
*_, labels_img = read_stanford_labels().

Categories

Resources