The mat file contains the following:
data: [15×3000000 double]
data_length_sec: 600
sampling_frequency: 5000
channels: {1×15 cell}
This is the code to run:
preictal_tst = 'Patient_1/Patient_1_preictal_segment_0001.mat'
preictal_data = scipy.io.loadmat(preictal_tst)
preictal_array = preictal_data['preictal_segment_1'][0][0][0]
l = list(range(10000))
for i in l[::5000]:
print('Preictal')
i_secs = preictal_array[0][i:i+5000]
print(i_secs)
i_f, i_t, i_Sxx = spectrogram(i_secs, fs=5000, return_onesided=False)
print(i_f)
print(i_t)
print(i_Sxx)
i_SS = np.log1p(i_Sxx)
print(i_SS)
plt.imshow(i_SS[:] / np.max(i_SS), cmap='gray')
plt.show()
In the link is the image of how the signal looks like
https://i.stack.imgur.com/PSZSe.jpg
Its formatted by storing each of the following variables (i_f, i_t, i_Sxx to the outcome of the function spectrogram when (i_secs, fs=5000, return_onesided=False) is passed to it.
The question is really unclear though and I doubt that answer made it any clearer so please edit with a more specific question if you still have any
Related
For my current assignment, I am to establish the stability of intersection/equilibrium points between two nullclines, which I have defined as follows:
def fNullcline(F):
P = (1/k)*((1/beta)*np.log(F/(1-F))-c*F+v)
return P
def pNullcline(P):
F = (1/delta)*(pD-alpha*P+(r*P**2)/(m**2+P**2))
return F
I also have a method "stability" that applies the Hurwitz criteria on the underlying system's Jacobian:
def dPdt(P,F):
return pD-delta*F-alpha*P+(r*P**2)/(m**2+P**2)
def dFdt(P,F):
return s*(1/(1+sym.exp(-beta*(-v+c*F+k*P)))-F)
def stability(P,F):
x = sym.Symbol('x')
ax = sym.diff(dPdt(x, F),x)
ddx = sym.lambdify(x, ax)
a = ddx(P)
# shortening the code here: the same happens for b, c, d
matrix = [[a, b],[c,d]]
eigenvalues, eigenvectors = np.linalg.eig(matrix)
e1 = eigenvalues[0]
e2 = eigenvalues[1]
if(e1 >= 0 or e2 >= 0):
return 0
else:
return 1
The solution I was looking for was later provided. Basically, values became too small! So this code was added to make sure no too small values are being used for checking the stability:
set={0}
for j in range(1,210):
for i in range(1,410):
x=i*0.005
y=j*0.005
x,y=fsolve(System,[x,y])
nexist=1
for i in set:
if(abs(y-i))<0.00001:
nexist=0
if(nexist):
set.add(y)
set.discard(0)
I'm still pretty new to coding so the function in and on itself is still a bit of a mystery to me, but it eventually helped in making the little program run smoothly :) I would again like to express gratitude for all the help I have received on this question. Below, there are still some helpful comments, which is why I will leave this question up in case anyone might run into this problem in the future, and can find a solution thanks to this thread.
After a bit of back and forth, I came to realise that to avoid the log to use unwanted values, I can instead define set as an array:
set = np.arange(0, 2, 0.001)
I get a list of values within this array as output, complete with their according stabilities. This is not a perfect solution as I still get runtime errors (in fact, I now get... three error messages), but I got what I wanted out of it, so I'm counting that as a win?
Edit: I am further elaborating on this in the original post to improve the documentation, however, I would like to point out again here that this solution does not seem to be working, after all. I was too hasty! I apologise for the confusion. It's a very rocky road for me. The correct solution has since been provided, and is documented in the original question.
I'm trying to resample a set of GRIB2 arrays at 0.25 degree resolution to a coarser 0.5 degree resolution using the xESMF package (xarray's coarsen method does not work here because there is an odd number of coordinates in the latitude).
I have converted the GRIB data to xarray format through the pygrib package, which then subsets out the specific grid I need:
fhr = 96
gridDefs = {
"0.25":
{'url': "https://noaa-gefs-retrospective.s3.amazonaws.com/landsfc.pgrb2.0p25"},
"0.5":
{'url': "https://noaa-gefs-retrospective.s3.amazonaws.com/landsfc.pgrb2.0p50"},
}
fileDefs = {
"0.25":
{'url': "https://noaa-gefs-retrospective.s3.amazonaws.com/GEFSv12/reforecast/2019/2019051900/c00/Days%3A1-10/tmp_pres_2019051900_c00.grib2",
'localfile': "tmp_pres.grib2"},
"0.5":
{'url': "https://noaa-gefs-retrospective.s3.amazonaws.com/GEFSv12/reforecast/2019/2019051900/c00/Days%3A1-10/tmp_pres_abv700mb_2019051900_c00.grib2",
'localfile': "tmp_pres_abv_700.grib2"},
}
def grib_to_xs(grib, vName):
arr = xr.DataArray(grib.values)
arr = arr.rename({'dim_0':'lat', 'dim_1':'lon'})
xs = arr.to_dataset(name=vName)
return xs
gribs = {}
for key, item in gridDefs.items():
if not os.path.exists(item['url'][item['url'].rfind('/')+1:]):
os.system("wget " + item['url'])
lsGrib = pygrib.open(item['url'][item['url'].rfind('/')+1:])
landsea = lsGrib[1].values
gLats = lsGrib[1]["distinctLatitudes"]
gLons = lsGrib[1]["distinctLongitudes"]
gribs["dataset" + key] = xr.Dataset({'lat': gLats, 'lon': gLons})
lsGrib.close()
for key, item in fileDefs.items():
if not os.path.exists(item['localfile']):
os.system("wget " + item['url'])
os.system("mv " + item['url'][item['url'].rfind('/')+1:] + " " + item['localfile'])
for key, item in fileDefs.items():
hold = pygrib.open(item['localfile'])
subsel = hold.select(forecastTime=fhr)
#Grab the first item
gribs[key] = grib_to_xs(subsel[1], "TT" + key)
hold.close()
The above code downloads two constant files (landsfc) at the two grid domains (0.25 and 0.5), then downloads two GRIB files at each of the resolutions as well. I'm trying to resample the 0.25 degree GRIB file (tmp_pres.grib2) to a 0.5 degree domain as such:
regridder = xe.Regridder(ds, gribs['dataset0.5'], 'bilinear')
print(regridder)
ds2 = regridder(ds)
My issue is that I generate two warning messages when trying to use the regridder:
/media/robert/HDD/Anaconda3/envs/wrf-work/lib/python3.8/site-packages/xarray/core/dataarray.py:682: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
return key in self.data
/media/robert/HDD/Anaconda3/envs/wrf-work/lib/python3.8/site-packages/xesmf/backend.py:53: UserWarning: Latitude is outside of [-90, 90]
warnings.warn('Latitude is outside of [-90, 90]')
The output xarray does have the correct coordinates, however the values inside the grid are way off (Outside the maxima/minima of the finer resolution grid), and exhibit these strange banding patterns that make no physical sense.
What I would like to know is, is this the correct process to upscale an array using xEMSF, and if not, how would I address the problem?
Any assistance would be appreciated, thanks!
I would recommend first trying conservative instead of bilinear (it's recommended on their documentation) and maybe check if you're using the parameters correctly because it seems something is wrong, my first guess would be that something you're doing moves the latitud around for some reason, I'm leaving the docs link here and hope someone knows more.
Regridder docs:
https://xesmf.readthedocs.io/en/latest/user_api.html?highlight=regridder#xesmf.frontend.Regridder.__init__
Upscaling recommendation (search for upscaling, there's also a guide for increasing resolution):
https://xesmf.readthedocs.io/en/latest/notebooks/Compare_algorithms.html?highlight=upscaling
Thanks to the documentation links and recommendations provided by MASACR 99, I was able to do some more digging into the xESMF package and to find a working example of resampling methods from the package author (https://github.com/geoschem/GEOSChem-python-tutorial/blob/main/Chapter03_regridding.ipynb), my issue was solved by two changes:
I changed the method from bilinear to conservative (This required also adding in two fields to the input array (boundaries for latitude and longitude).
Instead of directly passing the variable being resampled to the resampler, I instead had to define two fixed grids to create the resampler, then pass individual variables.
To solve the first change, I created a new function to give me the boundary variables:
def get_bounds(arr, gridSize):
lonMin = np.nanmin(arr["lon"].values)
latMin = np.nanmin(arr["lat"].values)
lonMax = np.nanmax(arr["lon"].values)
latMax = np.nanmax(arr["lat"].values)
sizeLon = len(arr["lon"])
sizeLat = len(arr["lat"])
bounds = {}
bounds["lon"] = arr["lon"].values
bounds["lat"] = arr["lat"].values
bounds["lon_b"] = np.linspace(lonMin-(gridSize/2), lonMax+(gridSize/2), sizeLon+1)
bounds["lat_b"] = np.linspace(latMin-(gridSize/2), latMax+(gridSize/2), sizeLat+1).clip(-90, 90)
return bounds
For the second change, I modified the regridder definition and application to use the statically defined grids, then passed the desired variable to resample:
regridder = xe.Regridder(get_bounds(gribs['dataset0.25'], 0.25), get_bounds(gribs['dataset0.5'], 0.5), 'conservative')
print(regridder)
ds2 = regridder(ds)
(Sorry for my english...)
I'm looking for a method to creat a plot.title which depends of my variables already defined at the begining.
I'm not asking you to make it for me. Just to help me to find documents, sites, forum or things like that. I haven't find in on Google and i don't know what to type coz english isn't my native language.
Currently, i'm showing a graph and creating a pdf. which also contain the graph, like that :
graphic = plt.figure(1)
plt.plot(ts, xs, label="Position")
plt.plot(ts, vs, label="Velocity")
plt.title("euler-k-10-c-0.1-dt-0.01")
plt.legend()
plt.xlabel("Time ts")
plt.ylabel("Valors of position xs and velocity vs")
plt.show()
pp = PdfPages("Graphics.pdf")
pp.savefig(graphic, dpi = 300, transparent = True)
pp.close()
What i want to, is to modify this line :
plt.title("euler-k-10-c-0.1-dt-0.01")
I'm supposed to enter the valors of k, c and dt variables, and i want to change the name of the graphic to make it concur with the valors choosen for these variables.
For example, my code ask to enter the valors of k, c and dt, so i enter :
k = 1 ; c = 0 ; dt = 0.1
Then the graph title is : euler-k-1-c-0-dt-0.1
Thank you very much !
The string entering the plot title can be composed of variables like any other string. In your particular case, something like
k = 1
c = 0
dt = 0.1
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
would do the job.
Here we've used formatted string literals; for other approaches to formatting a string, see e.g. this overview.
def make_plots(tx,xs,k,c,dt)
graphic = plt.figure(1)
plt.plot(ts, xs, label="Position")
plt.plot(ts, vs, label="Velocity")
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
plt.legend()
plt.xlabel("Time ts")
plt.ylabel("Valors of position xs and velocity vs")
plt.show()
pp = PdfPages("Graphics.pdf")
pp.savefig(graphic, dpi = 300, transparent = True)
pp.close()
Make a function and call it as often as you change your k,c and dt.
Ow ! Thank you, i didn't think i was that easy.
Make a function and call it as often as you change your k,c and dt.
Hum.. Yes thank you ! But that's not the point haha.
this :
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
answer my question. It works ! Now i can do that :
k = int(input("Enter the valor of k : "))
And the valor of k that i entered is considered in the title of my graph !
Thanks !
PS : I was also wondering why there was an error message when i wrote it :
k = input("Enter the valor of k : ")
It's because the "thing" you write when the input is executed, is considered as a string, and not an integer or a float ! So i have to add int() to make it works !
Thank you guys, you're awesome !
I'm trying to change the output of an exponential string formatting. I've fitted a curve to some data and would like to write these into the plot. Problem is, the x e-y format doesn't look nice, is there a posibility to change it so x * 10^-y?
Here is an example of the code I'm working with:
plt.plot(x, y, 'x', label = '$f(t) = {a:.0f} \cdot x + {b:.2e}$'.format(a = para[0], b = para[1])
a is some number bigger than 10000, that's why there is no need for decimalnumbers, but b is around 10^-7. Writing it as a float is spacewasting for the leading 0s, but the e^-7 doesn't look nice for publishing, that why I would like to change the output of the e-formatter, so it gives \cdot 10^{-7} (the \cdot {} for LaTeX) back.
Thanks
I would suggest you write an ad-hoc function to format the number in the output you want, something like this:
import numpy as np
def myformat(x):
myexp = np.floor(np.log10(x))
xout = x*10**(-myexp)
strout = "{:.2f} \times 10^{}".format(xout, myexp)
return strout
All, that need to be formated in LaTex style, must be wrapped with $ sign:
label='$f(t)$ = $x$ $\cdot$10$^-$$^7$'
Sign ^ makes aftergoing char as superscript (x$^5$ will give x to the power of 5) and _ is using for subscript (x$_5$ will give you x with index 5)
It's not clear to me from the documentation
http://python-xlib.sourceforge.net/doc/html/python-xlib_toc.html
how I could deterministically check whether a given display output (eg: HDMI-1) is extending or mirroring other display output.
the get_output_info method in the example bellow does not contain any information from which I could derive that.
from Xlib import X, display, Xutil
from Xlib.ext import randr
d = display.Display()
root = d.screen().root
resources = root.xrandr_get_screen_resources()._data
outputs = []
for output in resources['outputs']:
_data = d.xrandr_get_output_info(output,
resources['config_timestamp'])._data
Is it possible?
if so, how please?
Thank you!
With the following you can get x,y coordinates of framebuffer of a crtc of given output (from which you can derive whether given output is cloned or extended):
crtcInfo = d.xrandr_get_crtc_info(_data['crtc'],
resources['config_timestamp'])
x = crtcInfo.x
y = crtcInfo.y
The following helped me to understand the problem:
https://www.x.org/wiki/Development/Documentation/HowVideoCardsWork/#index3h3