I'm using scipy signaltonoise function below is the code but it returns an error. I searched regarding this in github too but couldn't find it. Can you please help.
import numpy as np
import cv2
import math
import os
import csv
from scipy import stats
from PIL import Image
from skimage.color import rgb2gray
from multiprocessing import Pool
from skimage.feature import local_binary_pattern # Local Binary Pattern function
from scipy.stats import itemfreq # To calculate a normalized histogram
import scipy.stats as sp
from skimage.feature import hog
from scipy.ndimage.measurements import label
from scipy import signal as sg
def calc_snr(img):
snr = stats.signaltonoise(img, axis=None)
return snr
snr = calc_snr(img)
scipy.stats.signaltonoise() was deprecated in scipy 0.16.0 and removed in 1.0.0. If you need to use the function without downgrading scipy, you can see the original code from the function before it was removed on github here, and reproduced below:
import numpy as np
def signaltonoise(a, axis=0, ddof=0):
a = np.asanyarray(a)
m = a.mean(axis)
sd = a.std(axis=axis, ddof=ddof)
return np.where(sd == 0, 0, m/sd)
Related
enter image description here
enter image description here
import SpatialDE
import numpy as np
import anndata
import scanpy as sc
import cv2
from sklearn.metrics import silhouette_score
from sklearn import metrics
import scanpy as sc
import pandas as pd
from decimal import Decimal
from decimal import Decimal,ROUND_HALF_UP
mousebrain_after_normalization_path='/home/user/imputation_test_data/MouseBrain_D1_normalization.h5ad'
adata_before = anndata.read_h5ad(mousebrain_after_normalization_path)
counts_before = pd.DataFrame(adata_before.X, columns=adata_before.var_names, index=adata_before.obs_names)
coord_before = pd.DataFrame(adata_before.obsm['spatial'], columns=['x', 'y'], index=adata_before.obs_names)
result_before = SpatialDE.run(coord_before, counts_before)
adata_before.obsm['spatialDE_result'] = result_before
I tried to use SpatialDE to evaluate my anndata on the computer server, I have transferred anndata.X to counts_before(which is a dataframe) and adata.obsm['spatial'] to be coord_before. and using SpatialDE.run to finish them. But no result.
I am using clr to import c# dll in python
one of the functions return ushort[,] ,
which is considered as System.UInt16[,] in python
How can in convert System.UInt16[,] to numpy uint16 matrix?
I can do the conversion only by looping on the matrix, reading each element and assigning its value to the respective position in another numpy matrix, but this solution is very slow.
Is there a faster conversion method which can utilize numpy vectorization ?
Here's a sample for my loop
import clr
import os
import numpy as np
dll_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), ("mydll") + ".dll")
clr.AddReference(dll_name)
from mynamespace import myclass
myobject = myclass()
numpy_matrix = np.empty([80,260],dtype = np.uint16)
SystemInt16_matrix = myobject.Getdata()
for i in range(20):
for j in range(32):
numpy_matrix[i,j]=SystemInt16_matrix[i,j]
I could find the solution, instead of the loop I should use np.fromiter & reshape
import clr
import os
import numpy as np
dll_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), ("mydll") + ".dll")
clr.AddReference(dll_name)
from mynamespace import myclass
myobject = myclass()
SystemInt16_matrix = myobject.Getdata()
numpy_matrix = np.fromiter(SystemInt16_matrix, np.int16).reshape((20, 32))
I need to solve this two equations simultaneously in python :
"b" is constant; but I don't know how to put the function "P" and its derivative at same time in the second equations code,
is there anyone could help me?
edition:
I have wrote this code to solve the question, but I don't know it is correct or not. is this code correctly gives the answer of those equations?
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import scipy.integrate as sy
import sys
import numpy as np
np.set_printoptions(threshold=sys.maxsize)
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
b=2
def eq(t,u):
#u[0] is p and u[1] is p', u[2]=y, u[3]=y'.
u[1]=u[0]*np.sqrt(0.25*(u[0]**-4)*(u[0]+(1/7)+0.7)
return [u[0],u[1],u[3],-3*(u[1]/(b*u[0]))*u[3] - u[2]]
u0 = [0.00001,0.00001,1.22*(10**28),0]
t = np.linspace(0.0000000001,0.6924*10**33,10000)
sol=solve_ivp(eq,t,u0,None)
I have the following MATLAB code that works fine using text data files, now I am trying to rewrite it using Python but running into errors. I have results that I am trying to apply some calculations on (perform data analysis). My results are in the format of binary files and I have a specific package I am using to help me import the data. For example, here ne is a 1024x256 array with 159 number of files printed per each iteration. So, in MATLAB I can simply do the following:
% Load data:
frame = 6; % how many number of output files
ne_bg = load([DirPath '/ne_unpert.txt']);
ne_p = load([DirPath '/ne_' num2str(frame) '.txt']);
% perform calculations on data:
ne = ne_bg + ne_p;
dn_over_n = ne_p ./ ne;
Since MATLAB deals easily with multi-dimensional arrays and matrices, I am struggling to interpret that to python.
My Python code:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
import matplotlib.colors as colors
import matplotlib.patches as patches
import scipy.optimize as opt
from scipy.special import erf, comb, gamma, gammainc
import scipy.constants as const
from scipy.integrate import odeint
import sys
from glob import glob
from mpl_toolkits.axes_grid1 import make_axes_locatable
import Package as pg
# Initialize sizes
ne = np.zeros((1024,256))
ne_p = np.zeros((1024,256))
# Data
data = pg.GData('ne_p.bp')
dg = pg.GInterpModal(data, 2, 'ms')
#dg.interpolate(overwrite=True)
ne_p = data.getValues()
data = pg.GData('ne0.gkyl')
dg = pg.GInterpModal(data, 2, 'ms')
#dg.interpolate(overwrite=True)
ne_bg = data.getValues()
for i in range(1,159): # would like to look at files start from 1 to 159 not 0
data = pg.GData('ne{:d}.gkyl'.format(i))
dg = pg.GInterpModal(data, 2, 'ms')
ne[i,:] = data.getValues() # ERROR HERE
dn_over_n = ne_p/ne # get
....
Error message:
ValueError Traceback (most recent call last)
<ipython-input-35-d6134fb807e8> in <module>
48 dg = pg.GInterpModal(data, 2, 'ms')
49 #dg.interpolate(overwrite=True)
---> 50 ne[i,:] = data.getValues()
ValueError: could not broadcast input array from shape (1024,256,1) into shape (256)
Can someone show me how to fix this and explain what it means?
I am trying to solve a simple differential equation using odeint function. It is giving an error with matching size of array. I think my initial_condi is not matching with the equation function. I can't figure it out where actually the error is. Blow is the error and code. Any help would be greatly appreciated.
RuntimeError: The size of the array returned by func (1) does not match the size of y0 (3)
from scipy import *
from scipy.integrate import odeint
from operator import itemgetter
import matplotlib as plt
from matplotlib.ticker import FormatStrFormatter
from pylab import *
from itertools import product
import itertools
from numpy import zeros_like
import operator
initial_condi = [1, 1, 1]
t_range = arange(0.0,60.0,1.0)
def equation(w, t):
T,I,V = w
dT= V*I*10.24-T*1.64
return dT
result_init = odeint(equation, initial_condi, t_range)
plt.plot(t, result_init[:, 0])
plt.show()
As your state vector has 3 components, the return value of the ODE function also needs to have 3 components, the derivatives of T,I,V. You only provided dT, but should return [dT, dI, dV ].