Trying to use add = True and I get an error message - spatial

I am Trying to use add = True and I get an error message. How can I do it?
This is my code
quadratcount(schools.pp)
plot(schools.sp, col = "red")
plot(quadratcount(schools.pp), add= T)`
and this is the error message I get
Error in (function (x, y = NULL, density = NULL, angle = 45, border = NULL, : plot.new has not been called yet

Looks like you made a simple typo: In the first plot command you write plot(schools.sp, col = "red"), where you probably meant plot(schools.pp, col = "red"). For future questions please provide a reproducible example where we can run each line including library(spatstat) and the definition of schools.pp etc. If you can't share your data just either:
use the first few points of your data
use a built-in dataset
generate artificial data

Related

In Networkx is there a way to select when to save to a file, when show on screen and when both?

At the moment, I am doing both:
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.savefig('graph.jpg')
I would like to be able to select if to display, save or both (what I am doing now)
There is no built-in option for that in networkx. One option is to wrap the code in a function along these lines:
def custom(G, plot=True, save_file=False):
'''plots G by default. save_file should be a string'''
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
if save: plt.savefig(save) # can allow custom save name
if plot: plt.show()
return
Note that if the figure displays regardless of the option passed to the command, then the inline option might need to be disabled.

question for dask output when using dask.array.map_overlap

I would like to use dask.array.map_overlap to deal with the scipy interpolation function. However, I keep meeting errors that I cannot understand and hoping someone can answer this to me.
Here is the error message I have received if I want to run .compute().
ValueError: could not broadcast input array from shape (1070,0) into shape (1045,0)
To resolve the issue, I started to use .to_delayed() to check each partition outputs, and this is what I found.
Following is my python code.
Step 1. Load netCDF file through Xarray, and then output to dask.array with chunk size (400,400)
df = xr.open_dataset('./Brazil Sentinal2 Tile/' + data_file +'.nc')
lon, lat = df['lon'].data, df['lat'].data
slon = da.from_array(df['lon'], chunks=(400,400))
slat = da.from_array(df['lat'], chunks=(400,400))
data = da.from_array(df.isel(band=0).__xarray_dataarray_variable__.data, chunks=(400,400))
Step 2. declare a function for da.map_overlap use
def sumsum2(lon,lat,data, hex_res=10):
hex_col = 'hex' + str(hex_res)
lon_max, lon_min = lon.max(), lon.min()
lat_max, lat_min = lat.max(), lat.min()
b = box(lon_min, lat_min, lon_max, lat_max, ccw=True)
b = transform(lambda x, y: (y, x), b)
b = mapping(b)
target_df = pd.DataFrame(h3.polyfill( b, hex_res), columns=[hex_col])
target_df['lat'] = target_df[hex_col].apply(lambda x: h3.h3_to_geo(x)[0])
target_df['lon'] = target_df[hex_col].apply(lambda x: h3.h3_to_geo(x)[1])
tlon, tlat = target_df[['lon','lat']].values.T
abc = lNDI(points=(lon.ravel(), lat.ravel()),
values= data.ravel())(tlon,tlat)
target_df['out'] = abc
print(np.stack([tlon, tlat, abc],axis=1).shape)
return np.stack([tlon, tlat, abc],axis=1)
Step 3. Apply the da.map_overlap
b = da.map_overlap(sumsum2, slon[:1200,:1200], slat[:1200,:1200], data[:1200,:1200], depth=10, trim=True, boundary=None, align_arrays=False, dtype='float64',
)
Step 4. Using to_delayed() to test output shape
print(b.to_delayed().flatten()[0].compute().shape, )
print(b.to_delayed().flatten()[1].compute().shape)
(1065, 3)
(1045, 0)
(1090, 3)
(1070, 0)
which is saying that the output from da.map_overlap is only outputting 1-D dimension ( which is (1045,0) and (1070,0) ), while in the da.map_overlap, the output I am preparing is 2-D dimension ( which is (1065,3) and (1090,3) ).
In addition, if I turn off the trim argument, which is
c = da.map_overlap(sumsum2,
slon[:1200,:1200],
slat[:1200,:1200],
data[:1200,:1200],
depth=10,
trim=False,
boundary=None,
align_arrays=False,
dtype='float64',
)
print(c.to_delayed().flatten()[0].compute().shape, )
print(c.to_delayed().flatten()[1].compute().shape)
The output becomes
(1065, 3)
(1065, 3)
(1090, 3)
(1090, 3)
This is saying that when trim=True, I cut out everything?
because...
#-- print out the values
b.to_delayed().flatten()[0].compute()[:10,:]
(1065, 3)
array([], shape=(1045, 0), dtype=float64)
while...
#-- print out the values
c.to_delayed().flatten()[0].compute()[:10,:]
array([[ -47.83683837, -18.98359832, 1395.01848583],
[ -47.8482856 , -18.99038681, 2663.68391094],
[ -47.82800624, -18.99207069, 1465.56517187],
[ -47.81897323, -18.97919009, 2769.91556363],
[ -47.82066663, -19.00712956, 1607.85927095],
[ -47.82696896, -18.97167714, 2110.7516765 ],
[ -47.81562653, -18.98302933, 2662.72112163],
[ -47.82176881, -18.98594465, 2201.83205114],
[ -47.84567 , -18.97512514, 1283.20631652],
[ -47.84343568, -18.97270783, 1282.92117225]])
Any thoughts for this?
Thank You.
I guess I got the answer. Please let me if I am wrong.
I am not allowing to use trim=True is because I change the shape of output array (after surfing the internet, I notice that the shape of output array should be the same with the shape of input array). Since I change the shape, the dask has no idea how to deal with it so it returns the empty array to me (weird).
Instead of using trim=False, since I didn't ask cutting-out the buffer zone, it is now okay to output the return values. (although I still don't know why the dask cannot concat the chunked array, but believe is also related to shape)
The solution is using delayed function on da.concatenate, which is
delayed(da.concatenate)([e.to_delayed().flatten()[idx] for idx in range(len(e.to_delayed().flatten()))])
In this case, we are not relying on the concat function in map_overlap but use our own concat to combine the outputs we want.

Index values from table into another table

I want to store the values by selecting the keys of a table into another table, for example:
polyline = {color="blue", thickness=2, npoints=4}
stuff = {"polyline.color":[polyline.thickness]}
print(stuff)
Should produce:
blue 2
However, I get the following error:
input:3: '}' expected near ':'
local polyline = {color="blue", thickness=2, npoints=4}
local stuff = {polyline.color, polyline.thickness}
print(table.unpack(stuff))
I believe, You're mixing in some Python syntax. Do you notice using two different (wrong) ways of accessing the values?
I guess, this is what You've meant with your snippet of Lua code:
polyline = {color = "blue", thickness = 2, npoints = 4}
stuff = {[polyline.color] = polyline.thickness}
for key, val in pairs(stuff) do
print(key, val)
end

Adding new elements to a table that has already been saved

So, I am working on a premium code system where you can input a secret code and if the code is valid, it will reward you based on what code you have used. Pretty simple idea, however, I have some trouble with it.
I have a table with all the codes that looks something like this:
GameState.PremiumCodesTable = GameState.PremiumCodesTable or {{code = "X45", value = 30}, {code = "MM4", value = 45}, {code = "B47", value = 100}}
Basically, if the game runs for the first time, the GameState.PremiumCodesTable will be nil and it will create new element in GameState table which is this table: {{code = "X45", value = 30}, {code = "MM4", value = 45}, {code = "B47", value = 100}}
Now, when the user uses the valid code, it gets deleted from the table. Eventually the user will find all the codes, use them and the GameState.PremiumCodesTable table will be empty.
Now, I want to update the game and bring in some new codes to find. However, since the GameState.PremiumCodesTable is already empty and saved, it will always be empty.
How can I add more codes later on?
I have a solution, but I don't like it, so I am asking here. My solution is to add code by code like so:
GameState.PremiumCodesTable[1] = GameState.PremiumCodesTable[1] or {code = "X45", value = 30}
GameState.PremiumCodesTable[2] = GameState.PremiumCodesTable[2] or {code = "MM4", value = 45}
GameState.PremiumCodesTable[3] = GameState.PremiumCodesTable[3] or {code = "B47", value = 100}
and so on... However, this takes too much space, so I'd like it to have in only ONE big table like the one above.
Use the save file to store an array of code strings that have been used, then initialize PremiumCodesTable to contain full data for all of the codes. That way, the save file keeps the bare minimum amount of information, and you get maximum freedom to process the save file however you want. (You may need to store the code data in a non-array table to make it easier to access.)
GameState.usedCodes = GameState.usedCodes or {}
local PremiumCodesTable = {
{code = "X45", value = 30},
{code = "MM4", value = 45},
{code = "B47", value = 100}
}

Correct syntax for using custom methods with caret package

I get the following error in caret trainControl() using the custom methods syntax documented in the package vignette (pdf) on page 46. Does anyone know if this document out of date or incorrect? It seems at odds with the caret documentation page where the "custom" parameter is not used.
> fitControl <- trainControl(custom=list(parameters=lpgrnn$grid, model=lpgrnn$fit,
prediction=lpgrnn$predict, probability=NULL,
sort=lpgrnn$sort, method="cv"),
number=10)
Error in trainControl(custom = list(parameters = lpgrnn$grid, model = lpgrnn$fit, :
unused argument (custom = list(parameters = lpgrnn$grid, model = lpgrnn$fit,
prediction = lpgrnn$predict, probability = NULL, sort = lpgrnn$sort, method = "cv",
number = 10))
The cited pdf is out of date. The caret website is the canonical source of documentation.

Resources