How to move a physical body to a specific point - physics

I am totally new to Corona, and I want to know that how to move a physical body to a specific point?

Here I derived formula for moving a physical body to a specific point
local force = 0.05 --Speed of body
local current_Position_X = myBody.x --myBody is a physical body which has to move
local current_Position_Y = myBody.y
local N_Movement_X = target.x - current_Position_X --target point where my body has to move
local N_Movement_Y = target.y - current_Position_Y
local N_Distance_X = N_Movement_X * N_Movement_X
local N_Distance_Y = N_Movement_Y * N_Movement_Y
local distance = math.sqrt(N_Distance_X + N_Distance_Y)
local unit = 1/distance
N_Movement_X = N_Distance_X * unit --Normalizing distance
N_Movement_Y = N_Distance_Y * unit --Normalizing distance
local forceX = distance * N_Movement_X
local forceY = distance * N_Movement_Y
myBody:setLinearVelocity(forceX*force, forceY* force)

Related

Is non-identical not enough to be considered 'distinct' for kmeans centroids?

I have an issue with kmeans clustering providing centroids. I saw the same problem already asked (
K-means: Initial centers are not distinct), but the solution in that post is not working in my case.
I selected the centroids using ClusterR::Kmeans_arma. I confirmed that my centroids are not identical using mgcv::uniquecombs, but still got the initial centers are not distinct error.
> dim(t(dat))
[1] 13540 11553
> centroids = ClusterR::KMeans_arma(data = t(dat), centers = 561,
n_iter = 50, seed_mode = "random_subset",
verbose = FALSE, CENTROIDS = NULL)
> dim(centroids)
[1] 561 11553
> x = mgcv::uniquecombs(centroids)
> dim(x)
[1] 561 11553
> res = kmeans(t(dat), centers = centroids, iter.max = 200)
Error in kmeans(t(dat), centers = centroids, iter.max = 200) :
initial centers are not distinct
Any suggestion to resolve this? Thanks!
I replicated the issue you've mentioned with the following data:
cols = 13540
rows = 11553
set.seed(1)
vec_dat = runif(rows * cols)
dat = matrix(vec_dat, nrow = rows, ncol = cols)
dim(dat)
dat = t(dat)
dim(dat)
There is no 'centers' parameter in the 'ClusterR::KMeans_arma()' function, therefore I've assumed you actually mean 'clusters',
centroids = ClusterR::KMeans_arma(data = dat,
clusters = 561,
n_iter = 50,
seed_mode = "random_subset",
verbose = TRUE,
CENTROIDS = NULL)
str(centroids)
dim(centroids)
The 'centroids' is a matrix of class "k-means clustering". If your intention is to come to the clusters then you can use,
clust = ClusterR::predict_KMeans(data = dat,
CENTROIDS = centroids,
threads = 6)
length(unique(clust)) # 561
class(centroids) # "k-means clustering"
If you want to pass the 'centroids' to the base R 'kmeans' function you have to set the 'class' of the 'centroids' object to NULL and that because the base R 'kmeans' function uses internally the base R 'duplicated()' function (you can view this by using print(kmeans) in the R console) which does not recognize the 'centroids' object as a matrix or data.frame (it is an object of class "k-means clustering") and performs the checking column-wise rather than row-wise. Therefore, the following should work for your case,
class(centroids) = NULL
dups = duplicated(centroids)
sum(dups) # this should actually give 0
res = kmeans(dat, centers = centroids, iter.max = 200)
I've made a few adjustments to the "ClusterR::predict_KMeans()" and particularly I've added the "threads" parameter and a check for duplicates, therefore if you want to come to the clusters using multiple cores you have to install the package from Github using,
remotes::install_github('mlampros/ClusterR',
upgrade = 'always',
dependencies = TRUE,
repos = 'https://cloud.r-project.org/')
The changes will take effect in the next version of the CRAN package which will be "1.2.2"
UPDATE regarding output and performance (based on your comment):
data(dietary_survey_IBS, package = 'ClusterR')
kmeans_arma = function(data) {
km_cl = ClusterR::KMeans_arma(data,
clusters = 2,
n_iter = 10,
seed_mode = "random_subset",
seed = 1)
pred_cl = ClusterR::predict_KMeans(data = data,
CENTROIDS = km_cl,
threads = 1)
return(pred_cl)
}
km_arma = kmeans_arma(data = dietary_survey_IBS)
km_algos = c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen")
for (algo in km_algos) {
cat('base-kmeans-algo:', algo, '\n')
km_base = kmeans(dietary_survey_IBS,
centers = 2,
iter.max = 10,
nstart = 1, # can be set to 5 or 10 etc.
algorithm = algo)
km_cl = as.vector(km_base$cluster)
print(table(km_arma, km_cl))
cat('--------------------------\n')
}
microbenchmark::microbenchmark(kmeans(dietary_survey_IBS,
centers = 2,
iter.max = 10,
nstart = 1, # can be set to 5 or 10 etc.
algorithm = algo), kmeans_arma(data = dietary_survey_IBS), times = 100)
I don't see any significant difference in the output clusters between the 'base R kmeans' and the 'kmeans_arma' function for all available 'base R kmeans' algorithms (you can test it also for your own data sets). I am not sure which algorithm the 'armadillo' library uses internally and moreover the 'base R kmeans' includes the 'nstart' parameter (you can consult the documentation for more info). Regarding performance you won't see any substantial differences for small to medium data sets but due to the fact that the armadillo library uses OpenMP internally in case that your computer has more than 1 cores then for big data sets I think the 'ClusterR::KMeans_arma' function will return the 'centroids' faster.

Perform Kriging Interpolation using Arcpy

I have list of point feature class. I am trying to write a python script to perform Krigging interpolation. I am getting error massage in this code "Point_Num" is not defined,
Below script i am working
import arcpy
from arcpy import env
from arcpy.sa import *
arcpy.env.overwriteOutput = True
# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")
In_Point = r"D:\NPP_Test\MERRA_TEMP_2012C" #(Point feature name:r001_mean, r002_mean.....r012_mean )
Out_Raster = r"D:\NPP_Test\MERRA_TEMP_2012D"
points = arcpy.ListFeatureClasses()
zFields = "GRID_CODE"
#Kriging Veriable
cellSize = 0.05
lagSize = 0.5780481172534
majorRange = 6
partialSill = 3.304292110
nugget = 0.002701348
kRadius = RadiusFixed(20000, 1)
#Mask region of interest
mask = r"D:\Gujarta Shape file\GUJARATSTATE.shp"
for zField in zFields:
Point = Point_Num[:3]
kModelUniversalObj = KrigingModelUniversal("LINEARDRIFT", lagSize, majorRange, partialSill, nugget)
OutKriging = Kriging(inPointFeatures, zField, kModelUniversalObj, cellSize, kRadius)
#IDWMASk = ExtractByMask(outIDW, mask)
KrigMask = ExtractByMask(OutKriging, mask)
#Save outraster as the same name of input
KrigMask.save("r{}.tif".format(Point_Num))

Plotting a fits image with aplpy using the right wcs transformation

I want to plot a fits file with aplpy but I get the following error:
INFO: The WCS transformation has more axes (3) than the image it is associated with (2) [astropy.wcs.wcs]
ERROR: IndexError: list index out of range [aplpy.wcs_util]
If I delete the header key words CTYPE3, CD3_3, WAT3_001 then I don't get the error anymore, but when plotting the fits file I see that the WCS transformation has not been done properly with RA and DEC coordinates all over the place.
This is the header:
HCG89_halpha_plot.fits[2929,2881][real]: HCG89-SII
No bad pixels, min=0., max=0. (old)
Line storage mode, physdim [2929,2881], length of user area 5144 s.u.
Created Tue 15:40:54 28-Jan-2014, Last modified Thu 22:20:03 30-Jan-2014
Pixel file "HCG89_halpha_plot.fits" [ok]
ORIGIN = 'NOAO-IRAF FITS Image Kernel July 2003' / FITS file originator
IRAF-TLM= '2014-01-30T19:20:03' / Time of last modification
OBJECT = 'HCG89-SII' / Name of the object observed
DATE-OBS= '2013-10-11T00:14:11.700' / Date of observation
DATE = '2014-01-28T12:40:54' / Date Format is YYYY-MM-DD
TIME = '00:14:11.07 to 00:19:11.40' / ~ Start & Stop of Exposure
N_PARAM = 80 / Number of Parameters
TELESCOP= 'SOAR 4.1m'
INSTRUME= 'Goodman Spectrograph'
NOTES = ' '
RA = '21:20:09.042' / right ascension [hh:mm:ss.sss]
DEC = '-3:55:23.160' / declination [dd:mm:ss.sss]
AIRMASS = 1.13 / airmass at approx. start of exposure
UT = '00:14:10.9' / time at approx. start of exposure [UTC]
FOCUS = -1021.0 / SOAR telescope focus
MOUNT_AZ= 17.1482 / SOAR mount azimuth
MOUNT_EL= 62.2622 / SOAR mount elevation
ROTATOR = 228.003 / Nasymth cage rotator angle [deg]
POSANGLE= 360.0 / position angle [deg. E of N]
SEEING = -1.0 / DIMM seeing [arcsec]
LST = '20:50:17.4' / Local Sidereal Time [hh:mm:ss.sss]
OBSRA = '21:20:09.946' / target right ascension [hh:mm:ss.sss]
OBSDEC = '-3:55:32.480' / target declination [hh:mm:ss.sss]
CAM_ANG = 0.014461 / camera angle [deg]
GRT_ANG = 0.661 / grating angle [deg]
CAM_TARG= 0.0 / camera target [deg]
GRT_TARG= 0.661 / grating target [deg]
CAM_FOC = 660 / camera focus
COLL_FOC= 1002 / collimator focus
FILTER = 'SII ' / primary filter wheel
FILTER2 = '<NO FILTER>' / secondary filter wheel
GRATING = '<NO GRATING>' / VPH grating [1/mm]
SLIT = '<NO MASK>' / slit [arcsec]
COL_TEMP= 10.421875 / coll ext temp (deg C)
CAM_TEMP= 14.234375 / cam ext temp (deg C)
EXPTIME = 300.0 / integration time
RDNOISE = 4.74 / CCD readnoise [e-]
GAIN = 1.4 / CCD gain [e-/ADU]
OBSTYPE = 'OBJECT ' / observation type
OBSERVER= ' '
PROPOSAL= ' '
EQUINOX = 2000.0 / equinox of coordinates
CRPIX1 = 1477.39599990845 / Reference pixel on axis 1
CRPIX2 = 1488.23082170899 / Reference pixel on axis 2
CRVAL1 = 320.041401353 / Value at ref. pixel on axis 1
CRVAL2 = -3.91652009277 / Value at ref. pixel on axis 2
CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1
CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2
PC1_1 = 0.999884048946387 / Transformation matrix element
PC1_2 = 0.0152278909432213 / Transformation matrix element
PC2_1 = -0.0140395410920601 / Transformation matrix element
PC2_2 = 1.0 / Transformation matrix element
MJD-OBS = 56576.0098576389 / Modified Julian Date of observation
RADESYS = 'FK5 ' / Reference frame for RA/DEC values
DISPAXIS= 1
DETSIZE = '[1:4096,1:4096]'
TRIMSEC = '[1:3096,1:3096]'
CCDSIZE = '[1:4096,1:4096]'
CCDSUM = '1 1 '
OPENTIME= '00:14:11.611' / GPS-Synched Time for Shutter Open (UT)
INSTRUME= 'Goodman Spectrograph'
COMMENT Triggered Acquisition, Exp Time= 05:00
WCSDIM = 3
LTM1_1 = 1.0
LTM2_2 = 1.0
LTM3_3 = 1.0
WAXMAP01= '1 0 2 0 0 0 '
WAT0_001= 'system=physical'
WAT1_001= 'wtype=linear axtype=ra'
WAT2_001= 'wtype=linear axtype=dec'
WAT3_001= 'wtype=linear'
LTV1 = -159.604000091553
LTV2 = -134.766998291016
IMCMB001= '0073.HCG89-SII_scaled.fits'
IMCMB002= '0074.HCG89-SII_scaled.fits'
IMCMB003= '0079.HCG89-SII_scaled.fits'
IMCMB004= '0080.HCG89-SII_scaled.fits'
IMCMB005= '0083.HCG89-SII_scaled.fits'
IMCMB006= '0084.HCG89-SII_scaled.fits'
NCOMBINE= 6
CTYPE3 = 'LINEAR '
CD1_1 = 4.03250815042544E-5
CD2_2 = 4.04084336509694E-5
CD3_3 = 1.
I am not sure because I don't have access to your image, but do you have a multi-extension FITS file? If you do you might have the same error I had (Find physical coordinates of a pixel in a fits file with python).
Check to make sure you are using the HDU and header that are connected to the science data.

Verlet integrator + friction

I have been following "A Verlet based approach for 2D game physics" on Gamedev.net and I have written something similar.
The problem I am having is that the boxes slide along the ground too much.
How can I add a simple rested state thing where the boxes will have more friction and only slide a tiny bit?
Just introduce a small, constant acceleration on moving objects that points in the direction opposite to the motion. And make sure it can't actually reverse the motion; if you detect that in an integration step, just set the velocity to zero.
If you want to be more realistic, the acceleration should derive from a force which is proportional to the normal force between the object and the surface it's sliding on.
You can find this in any basic physics text, as "kinetic friction" or "sliding friction".
At the verlet integration: r(t)=2.00*r(t-dt)-1.00*r(t-2dt)+2at²
change the multipliers to 1.99 and 0.99 for friction
Edit: this is more true:
r(t)=(2.00-friction_mult.)*r(t-dt)-(1.00-friction_mult.)*r(t-2dt)+at²
Here is a simple time stepping scheme (symplectic Euler method with manually resolved LCP) for a box with Coulomb friction and a spring (frictional oscillator)
mq'' + kq + mu*sgn(q') = F(t)
import numpy as np
import matplotlib.pyplot as plt
q0 = 0 # initial position
p0 = 0 # initial momentum
t_start = 0 # initial time
t_end = 10 # end time
N = 500 # time points
m = 1 # mass
k = 1 # spring stiffness
muN = 0.5 # friction force (slip and maximal stick)
omega = 1.5 # forcing radian frequency [RAD]
Fstat = 0.1 # static component of external force
Fdyn = 0.6 # amplitude of harmonic external force
F = lambda tt,qq,pp: Fstat + Fdyn*np.sin(omega*tt) - k*qq - muN*np.sign(pp) # total force, note sign(0)=0 used to disable friction
zero_to_disable_friction = 0
omega0 = np.sqrt(k/m)
print("eigenfrequency f = {} Hz; eigen period T = {} s".format(omega0/(2*np.pi), 2*np.pi/omega0))
print("forcing frequency f = {} Hz; forcing period T = {} s".format(omega/(2*np.pi), 2*np.pi/omega))
time = np.linspace(t_start, t_end, N) # time grid
h = time[1] - time[0] # time step
q = np.zeros(N+1) # position
p = np.zeros(N+1) # momentum
absFfriction = np.zeros(N+1)
q[0] = q0
p[0] = p0
for n, tn in enumerate(time):
p1slide = p[n] + h*F(tn, q[n], p[n]) # end-time momentum, assuming sliding
q1slide = q[n] + h*p1slide/m # end-time position, assuming sliding
if p[n]*p1slide > 0: # sliding goes on
q[n+1] = q1slide
p[n+1] = p1slide
absFfriction[n] = muN
else:
q1stick = q[n] # assume p1 = 0 at t=tn+h
Fstick = -p[n]/h - F(tn, q1stick, zero_to_disable_friction) # friction force needed to stop at t=tn+h
if np.abs(Fstick) <= muN:
p[n+1] = 0 # sticking
q[n+1] = q1stick
absFfriction[n] = np.abs(Fstick)
else: # sliding starts or passes zero crossing of velocity
q[n+1] = q1slide # possible refinements (adapt to slip-start or zero crossing)
p[n+1] = p1slide
absFfriction[n] = muN

Error when generating pdf using script in R

I'm using R to loop through the columns of a data frame and make a graph of the resulting analysis. I don't get any errors when the script runs, but it generates a pdf that cannot be opened.
If I run the content of the script, it works fine. I wondered if there is a problem with how quickly it is looping through, so I tried to force it to pause. This did not seem to make a difference. I'm interested in any suggestions that people have, and I'm also quite new to R so suggestions as to how I can improve the approach are welcome too. Thanks.
for (i in 2:22) {
# Organise data
pop_den_z = subset(pop_den, pop_den[i] != "0") # Remove zeros
y = pop_den_z[,i] # Get y col
x = pop_den_z[,1] # get x col
y = log(y) # Log transform
# Regression
lm.0 = lm(formula = y ~ x) # make linear model
inter = summary(lm.0)$coefficients[1,1] # Get intercept
slop = summary(lm.0)$coefficients[2,1] # Get slope
# Write to File
a = c(i, inter, slop)
write(a, file = "C:/pop_den_coef.txt", ncolumns = 3, append = TRUE, sep = ",")
## Setup pdf
string = paste("C:/LEED/results/Images/R_graphs/Pop_den", paste(i-2), "City.pdf")
pdf(string, height = 6, width = 9)
p <- qplot(
x, y,
xlab = "Radius [km]",
ylab = "Population Density [log(people/km)]",
xlim = x_range,
main = "Analysis of Cities"
)
# geom_abline(intercept,slope)
p + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1)
Sys.sleep(5)
### close the PDF file
dev.off()
}
The line should be
print(p + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1))
In pdf devices, ggplot (and lattice) only writes to file when explicitly printed.