How to use N4BiasCorrectionFilter with ITK? - itk

I'm trying to use ITK N4BiasCorrectionFilter for pre-processing in a MONAI U-Net:
class N4ITKTransform(Transform):
def __call__(self,image):
filtered = []
for channel in image["image"]:
# Crea un'immagine ITK dall'array NumPy
inputImage = itk.image_from_array(channel)
# Crea un filtro di correzione del bias field
corrector = itk.N4BiasFieldCorrectionImageFilter()
#corrector.SetInput(inputImage)
# Esegui il filtro
outputImage = corrector.Execute(inputImage)
# Crea un array NumPy dall'immagine ITK
filtered.append(itk.array_from_image(outputImage))
image["image"] = np.stack(filtered)
return image
monai_load = [
LoadImaged(keys=["image","segmentation"],image_only=False,reader=PILReader()),
EnsureTyped(keys=["image", "segmentation"], data_type="numpy"),
AddChanneld(keys=["segmentation","image"]),
#RepeatChanneld(keys=["segmentation"],repeats=2),
RepeatChanneld(keys=["image"],repeats=3),
AsChannelFirstd(keys=["image"], channel_dim = 0),
]
monai_transforms =[
AsDiscreted(keys=["segmentation"],threshold=0.5),
ToTensord(keys=["image","segmentation"]),
]
train_transforms = Compose(monai_load + [N4ITKTransform()] + monai_transforms)
I try to apply these transforms in a check dataset:
check_ds = Dataset(data=train_data, transform=train_transforms)
orig_ds = Dataset(data=train_data, transform=Compose(monai_load))
check_loader = DataLoader(check_ds, batch_size=1)
orig_loader = DataLoader(orig_ds, batch_size=1)
check_data = utils.first(check_loader)
orig_data = utils.first(orig_loader)
But when i run it the main problem seems to be:
"RuntimeError: C:\P\IPP\ITK-source\ITK\Modules\Core\Common\src\itkProcessObject.cxx:1339:
ITK ERROR: N4BiasFieldCorrectionImageFilter(0000019BDBD62A40): Input Primary is required but not set."
RuntimeError: applying transform <__main__.N4ITKTransform object at 0x0000019BF0CB5220>
RuntimeError: applying transform <monai.transforms.compose.Compose object at 0x0000019BF0CB52E0>
How can solve the Input problem?

ITK Python has a different syntax from SimpleITK. Take a look at quick start guide. It should be outputImage = itk.n4_bias_field_correction_image_filter(inputImage), or something similar to it.

Related

Missing arguments in a nested function

I follow a python course on finance about portfolio theory. I have to create a function with a nested function in it.
My problem is I have a error message of "neg_sharpe_ratio() missing 2 required positional arguments: 'er' and 'cov'" whereas to my mind 'er' and 'cov' are already defined in my function msr below. So I understand how they are missing.
from scipy.optimize import minimize
def msr(riskfree_rate, er, cov):
n= er.shape[0]
init_guess= np.repeat(1/n, n)
bounds=((0.00, 1.0),)*n
weights_sum_to_1 = {
'type' :'eq' , #
'fun' : lambda weights: np.sum(weights) - 1 ##
}
def neg_sharpe_ratio(weights,riskfree_rate, er, cov):
r = erk.portfolio_return(weights, er)
vol = erk.portfolio_vol(weights,cov)
return -(r-riskfree_rate)/vol
results = minimize( neg_sharpe_ratio, init_guess,
args=(cov,), method="SLSQP",
options={'disp': False},
constraints=( weights_sum_to_1),
bounds=bounds
)
return results.x
TypeError: neg_sharpe_ratio() missing 2 required positional arguments: 'er' and 'cov'
The function neg_sharpe_ratio is able to reference any of the variables passed in and made by the function msr without needing those same variables passed into it itself. Therefore you should be able to remove the paramters riskfree_rate, er, and cov from the neq_sharpe_ratio function definition and have it work, as those variables are passed into its parent function, leaving you with:
def neg_sharpe_ratio(weights):
For those who might be interested, I find my mistake..
Indeed, I forgot to define correctly the arguments of my function neg_share_ratio in my function minimize.
Here is the code amended:
from scipy.optimize import minimize
def msr(riskfree_rate, er, cov):
n= er.shape[0]
init_guess= np.repeat(1/n, n)
bounds=((0.00, 1.0),)*n
weights_sum_to_1 = {
'type' :'eq' , #
'fun' : lambda weights: np.sum(weights) - 1 ##
}
def neg_sharpe_ratio(weights,riskfree_rate, er, cov):
r = erk.portfolio_return(weights, er)
vol = erk.portfolio_vol(weights,cov)
return -(r-riskfree_rate)/vol
results = minimize( neg_sharpe_ratio, init_guess,
args=(weights,riskfree_rate,er,cov), method="SLSQP",
options={'disp': False},
constraints=( weights_sum_to_1),
bounds=bounds
)
return results.x code here

Retrieve Data from an API

I'm using an api in my browser similar to http://jsonplaceholder.typicode.com/users. The data returned is JSON in the exact same format.
The difference is that my api receives search parameters in brackets
url.com/search?type=XXXXX&q=[parameter]&limit=10000&locale=en_US
Has anyone come across a parameter that will retrieve all JSON from an api? I don't know if this possible to do..
So far I've tried passing: [all], [get], [""], [ ], []
hello the way I get it is as follows. you must create a database or an array as you want then make the following call. in my case i use one database.
importar json
solicitudes de importación
importar psycopg2
r = requests . get ( 'AppiURL' )
datajson = r . json ()
conexión a la base de datos
prueba :
conn = psycopg2 . connect ( "dbname = '' user = 'tu_usuari' host = 'localhost' password = 'tu_pswd'" )
except :
print "No puedo conectarme a la base de datos"
cursor = conn . cursor ()
cursor . executemany ( "INSERTAR en yourdatabasetable (Row1,Row2,row3) VALUES (% (id) s,% (paramname1) s,% (paramname2) s,......)" , dataJson [ 'somename' ])
conn . commit ()
cursor . cerrar ()

How use wikidata api to access to the statements

I'm trying to get information from Wikidata. For example, to access to "cobalt-70" I use the API.
API_ENDPOINT = "https://www.wikidata.org/w/api.php"
query = "cobalt-70"
params = {
'action': 'wbsearchentities',
'format': 'json',
'language': 'en',
'search': query
}
r = requests.get(API_ENDPOINT, params = params)
print(r.json())
So there is a "claims" which gives access to the statements. Is there a best way to check if a value exists in the statement? For example, "cobalt-70" have the value 0.5 inside the property P2114. So how can I check if a value exists in the statement of the entity? As this example.
Is there an approach to access it. Thank you!
I'm not sure this is exactly what you are looking for, but if it's close enough, you can probably modify it as necessary:
import requests
import json
url = 'https://www.wikidata.org/wiki/Special:EntityData/Q18844865.json'
req = requests.get(url)
targets = j_dat['entities']['Q18844865']['claims']['P2114']
for target in targets:
values = target['mainsnak']['datavalue']['value'].items()
for value in values:
print(value[0],value[1])
Output:
amount +0.5
unit http://www.wikidata.org/entity/Q11574
upperBound +0.6799999999999999
lowerBound +0.32
amount +108.0
unit http://www.wikidata.org/entity/Q723733
upperBound +115.0
lowerBound +101.0
EDIT:
To find property id by value, try:
targets = j_dat['entities']['Q18844865']['claims'].items()
for target in targets:
line = target[1][0]['mainsnak']['datavalue']['value']
if isinstance(line,dict):
for v in line.values():
if v == "+0.5":
print('property: ',target[0])
Output:
property: P2114
I try a solution which consists to search inside the json object as the solution proposed here : https://stackoverflow.com/a/55549654/8374738. I hope it can help. Let's give you the idea.
import pprint
def search(d, search_pattern, prev_datapoint_path=''):
output = []
current_datapoint = d
current_datapoint_path = prev_datapoint_path
if type(current_datapoint) is dict:
for dkey in current_datapoint:
if search_pattern in str(dkey):
c = current_datapoint_path
c+="['"+dkey+"']"
output.append(c)
c = current_datapoint_path
c+="['"+dkey+"']"
for i in search(current_datapoint[dkey], search_pattern, c):
output.append(i)
elif type(current_datapoint) is list:
for i in range(0, len(current_datapoint)):
if search_pattern in str(i):
c = current_datapoint_path
c += "[" + str(i) + "]"
output.append(i)
c = current_datapoint_path
c+="["+ str(i) +"]"
for i in search(current_datapoint[i], search_pattern, c):
output.append(i)
elif search_pattern in str(current_datapoint):
c = current_datapoint_path
output.append(c)
output = filter(None, output)
return list(output)
And you just need to use:
pprint.pprint(search(res.json(),'0.5','res.json()'))
Output:
["res.json()['claims']['P2114'][0]['mainsnak']['datavalue']['value']['amount']"]

Why the features are overwritten when extracted using pycaffe?

I observed that the features are overwritten when I extract them using pycaffe. My code is as follows:
tImg_1 = misc.imread('1.jpg')
tImg_1 = tImg_1[:,:,::-1] # color channel swap
tImg_2 = misc.imread('2.jpg')
tImg_2 = tImg_2[:,:,::-1] # color channel swap
tImg_1 = (np.float32(tImg_1)- 127.5)/128 # mean substruction
tImg_2 = (np.float32(tImg_2)- 127.5)/128 # mean substruction
tI_1 = np.moveaxis(tImg_1, 0, 1) # Transpose
tI_2 = np.moveaxis(tImg_2, 0, 1) # Transpose
# Extract features
tI_1 = np.reshape(tImg_1, (1, tImg_1.shape[2], tImg_1.shape[0], tImg_1.shape[1]))
tI_2 = np.reshape(tImg_2, (1, tImg_2.shape[2], tImg_2.shape[0], tImg_2.shape[1]))
net.blobs['data'].data[...] = tI_1
net.forward()
fts_1 = net.blobs['fc5'].data
print(fts_1[0, 0])
net.blobs['data'].data[...] = tI_2
net.forward()
fts_2 = net.blobs['fc5'].data
print(fts_2[0, 0])
print(fts_1[0, 0])
Executing this provides the following output:
0.508398
-0.176945
-0.176945
That means the values of fts_1 is overwritten by fts_2. How can I avoid this problem?
fts_1 is just pointing to net.blobs['fc5'].data. You need to make a deepcopy of the object. So your first assignment should be fts_1 = copy.deepcopy(net.blobs['fc5'].data)

Problem with spline method = 'monoH.FC''

I am interested in using the monotone spline, but I get an error when R tries to use it. I am using R 2.12.0, and the method 'monoH.FC' says that it has been supported since 2.8.0
Reproducible example (same result for more complicated (x,y) relationships)
x<-1:2
y<-1:2
spline(x,y,method="monoH.FC")
Error in spline(x, y, method = "monoH.FC") : invalid interpolation method
What I have tried
?spline returns:
...
Usage:
...
spline(x, y = NULL, n = 3*length(x), method = "fmm",
xmin = min(x), xmax = max(x), xout, ties = mean)
...
Arguments:
method: specifies the type of spline to be used. Possible values are
‘"fmm"’, ‘"natural"’, ‘"periodic"’ and ‘"monoH.FC"’.
...
But the spline function itself indicates that the 'monoH.FC' method is not supported:
...
method <- pmatch(method, c("periodic", "natural", "fmm"))
if (is.na(method))
stop("invalid interpolation method")
...
Question
How can I use method = 'monoH.FC' with spline?
Use splinefun; it supports method=monoH.FC.
The last example in ?spline shows you how to do it.
## An example of monotone interpolation
n <- 20
set.seed(11)
x. <- sort(runif(n)) ; y. <- cumsum(abs(rnorm(n)))
plot(x.,y.)
curve(splinefun(x.,y.)(x), add=TRUE, col=2, n=1001)
curve(splinefun(x.,y., method="mono")(x), add=TRUE, col=3, n=1001)
legend("topleft", paste("splinefun( \"", c("fmm", "monoH.CS"), "\" )", sep=''),
col=2:3, lty=1)