Here are the examples of the python api numpy.sign taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
925 Examples
3
Source : linearity_hypothesis.py
with MIT License
from 95616ARG
with MIT License
from 95616ARG
def fgsm(self, network, image, to_label, l_inf, process):
"""Returns an FGSM-perturbed version of @image.
@process should be the pre-processing function for @network, while
@to_label is the target label. @l_inf is the l_inf norm we respect.
"""
signs = np.sign(network.compute_gradients(
[process(image)], to_label))[0]
return self.perturb_l_inf(image, signs, l_inf)
def random_perturbation(self, image, l_inf, seed):
3
Source : featureExtraction.py
with MIT License
from abhirooptalasila
with MIT License
from abhirooptalasila
def zero_crossing_rate(frame):
"""Computes zero crossing rate of frame
"""
count = len(frame)
count_zero = np.sum(np.abs(np.diff(np.sign(frame)))) / 2
return np.float64(count_zero) / np.float64(count - 1.0)
def energy(frame):
3
Source : data.py
with MIT License
from acids-ircam
with MIT License
from acids-ircam
def sign_planes(args):
radius = .5#.1;
def get_label(point):
return (np.sign(point[0]) == np.sign(point[1])) * 1
pts_0, pts_1 = [], []
for i in range(args.toy_points):
x = np.random.uniform(-radius, radius)
y = np.random.uniform(-radius, radius)
noise_x = np.random.uniform(-radius, radius) * args.toy_noise
noise_y = np.random.uniform(-radius, radius) * args.toy_noise
if (get_label([x + noise_x, y + noise_y]) == 1):
pts_1.append([x, y])
else:
pts_0.append([x, y])
return pts_0, pts_1
"""
3
Source : atari_wrappers.py
with MIT License
from AcutronicRobotics
with MIT License
from AcutronicRobotics
def reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
class WarpFrame(gym.ObservationWrapper):
3
Source : test_pseudo_diffs.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def direct_hilbert(x):
fx = fft(x)
n = len(fx)
w = fftfreq(n)*n
w = 1j*sign(w)
return ifft(w*fx)
def direct_ihilbert(x):
3
Source : _cubic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _edge_case(h0, h1, m0, m1):
# one-sided three-point estimate for the derivative
d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1)
# try to preserve shape
mask = np.sign(d) != np.sign(m0)
mask2 = (np.sign(m0) != np.sign(m1)) & (np.abs(d) > 3.*np.abs(m0))
mmm = (~mask) & mask2
d[mask] = 0.
d[mmm] = 3.*m0[mmm]
return d
@staticmethod
3
Source : test_decomp.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_check_finite(self):
a = [[1,2,3],[1,2,3],[2,5,6]]
w,v = eig(a, check_finite=False)
exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2]
v0 = array([1,1,(1+sqrt(93)/3)/2])
v1 = array([3.,0,-1])
v2 = array([1,1,(1-sqrt(93)/3)/2])
v0 = v0 / sqrt(dot(v0,transpose(v0)))
v1 = v1 / sqrt(dot(v1,transpose(v1)))
v2 = v2 / sqrt(dot(v2,transpose(v2)))
assert_array_almost_equal(w,exact_w)
assert_array_almost_equal(v0,v[:,0]*sign(v[0,0]))
assert_array_almost_equal(v1,v[:,1]*sign(v[0,1]))
assert_array_almost_equal(v2,v[:,2]*sign(v[0,2]))
for i in range(3):
assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i])
def test_not_square_error(self):
3
Source : test_decomp.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _make_pos(X):
# the decompositions can have different signs than verified results
return np.sign(X)*X
class TestOrdQZ(object):
3
Source : mstats_basic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def msign(x):
"""Returns the sign of x, or 0 if x is masked."""
return ma.filled(np.sign(x), 0)
def pearsonr(x,y):
3
Source : _continuous_distns.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _stats(self, skew):
_, _, _, _, _, beta, alpha, zeta = (
self._preprocess([1], skew))
m = zeta + alpha / beta
v = alpha / (beta**2)
s = 2.0 / (alpha**0.5) * np.sign(beta)
k = 6.0 / alpha
return m, v, s, k
def _pdf(self, x, skew):
3
Source : _continuous_distns.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _cdf(self, x, beta):
c = 0.5 * np.sign(x)
# evaluating (.5 + c) first prevents numerical cancellation
return (0.5 + c) - c * sc.gammaincc(1.0/beta, abs(x)**beta)
def _ppf(self, x, beta):
3
Source : _continuous_distns.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _ppf(self, x, beta):
c = np.sign(x - 0.5)
# evaluating (1. + c) first prevents numerical cancellation
return c * sc.gammainccinv(1.0/beta, (1.0 + c) - 2.0*c*x)**(1.0/beta)
def _sf(self, x, beta):
3
Source : filters.py
with Apache License 2.0
from advboxes
with Apache License 2.0
from advboxes
def __call__(self, img_batch_np, threshold):
"""Squeeze image by binary filter
Parameters
----------
img_batch_np : array
Input image batch or image
threshold : float
Threshold for binarlize
"""
x_bin = np.maximum(np.sign(img_batch_np - threshold), 0)
return x_bin
class BinaryRandomFilter():
3
Source : dsp.py
with MIT License
from agheful
with MIT License
from agheful
def encode_mu_law(x: np.array, mu: float) -> np.array:
mu = mu - 1
fx = np.sign(x) * np.log(1 + mu * np.abs(x)) / np.log(1 + mu)
return np.floor((fx + 1) / 2 * mu + 0.5)
@staticmethod
3
Source : dsp.py
with MIT License
from agheful
with MIT License
from agheful
def decode_mu_law(y: np.array, mu: float, from_labels=True) -> np.array:
if from_labels:
y = DSP.label_2_float(y, math.log2(mu))
mu = mu - 1
x = np.sign(y) / mu * ((1 + mu) ** np.abs(y) - 1)
return x
3
Source : intermediate_lang.py
with MIT License
from aidangoettsch
with MIT License
from aidangoettsch
def point_loc_relative_to_line(segment, point):
segment_second_prime = Point(
segment[1].x - segment[0].x, segment[1].y - segment[0].y
)
point_prime = Point(point.x - segment[0].x, point.y - segment[0].y)
r = point_cross_product(segment_second_prime, point_prime)
return r if r == 0 else np.sign(r)
def a_sandwiches_b(segment_a, segment_b):
3
Source : test_interpretations.py
with Apache License 2.0
from aig-upf
with Apache License 2.0
from aig-upf
def test_special_function_sgn():
import numpy as np
from tarski.syntax.arithmetic.special import sgn
lang = tarski.fstrips.language(theories=[Theory.ARITHMETIC, Theory.SPECIAL])
model = Model(lang)
model.evaluator = evaluate
reals = lang.Real
x = lang.constant(0.5, reals)
assert model[sgn(x)].symbol == np.sign(0.5)
def test_random_function_normal():
3
Source : geometry.py
with MIT License
from aimuch
with MIT License
from aimuch
def check_side_of_line(point, line):
p1, p2 = line
det = (point[0] - p1[0]) * (p2[1] - p1[1]) - \
(point[1] - p1[1]) * (p2[0] - p1[0])
return np.sign(det)
def check_clockwise(points):
3
Source : regression.py
with MIT License
from akhilvasvani
with MIT License
from akhilvasvani
def grad(self, w):
l1_contr = self.l1_ratio * np.sign(w)
l2_contr = (1 - self.l1_ratio) * w
return self.alpha * (l1_contr + l2_contr)
class Regression(object):
3
Source : support_vector_machine.py
with MIT License
from akhilvasvani
with MIT License
from akhilvasvani
def predict(self, X):
y_pred = []
# Iterate through list of samples and make predictions
for sample in X:
prediction = 0
# Determine the label of the sample by the support vectors
for i in range(len(self.lagr_multipliers)):
prediction += self.lagr_multipliers[i] * self.support_vector_labels[
i] * self.kernel(self.support_vectors[i], sample)
prediction += self.intercept
y_pred.append(np.sign(prediction))
return np.array(y_pred)
3
Source : gym_utils.py
with MIT License
from akzaidi
with MIT License
from akzaidi
def step(self, action):
ob, rew, done, info = self.env.step(action)
if self.easy_freeway:
if rew > 0:
self.half_way_reward = 1
chicken_height = self.chicken_height(ob)
if chicken_height < 105:
rew += self.half_way_reward
self.half_way_reward = 0
if self.reward_clipping:
rew = np.sign(rew)
return ob, rew, done, info
def reset(self, **kwargs):
3
Source : svm.py
with MIT License
from alan-toledo
with MIT License
from alan-toledo
def svm_predict(state, matrix, radius):
M, N = matrix.shape
Xtrain = state['Xtrain']
Sqtrain = state['Sqtrain']
matrix = 1. * (matrix > 0)
squared = np.sum(matrix * matrix, axis=1)
gram = matrix.dot(Xtrain.T)
K = np.exp(-(squared.reshape((-1, 1)) + Sqtrain.reshape((1, -1)) - 2 * gram) / (2 * (radius ** 2)))
alpha_avg = state['alpha_avg']
preds = K.dot(alpha_avg)
output = (1 + np.sign(preds)) // 2
return output
3
Source : meshcut.py
with MIT License
from alexsax
with MIT License
from alexsax
def triangle_intersects_plane(mesh, tid, plane):
"""
Returns true if the given triangle is cut by the plane. This will return
false if a single vertex of the triangle lies on the plane
"""
dists = [point_to_plane_dist(mesh.verts[vid], plane)
for vid in mesh.tris[tid]]
side = np.sign(dists)
return not (side[0] == side[1] == side[2])
# ---- Planar cross-section
INTERSECT_EDGE = 0
3
Source : intervals.py
with Apache License 2.0
from alpha-xone
with Apache License 2.0
from alpha-xone
def shift_time(start_time, mins) -> str:
"""
Shift start time by mins
Args:
start_time: start time in terms of HH:MM string
mins: number of minutes (+ / -)
Returns:
end time in terms of HH:MM string
"""
s_time = pd.Timestamp(start_time)
e_time = s_time + np.sign(mins) * pd.Timedelta(f'00:{abs(mins)}:00')
return e_time.strftime('%H:%M')
class Intervals(object):
3
Source : scale.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def transform_non_affine(self, a):
sign = np.sign(a)
masked = ma.masked_inside(a,
-self.linthresh,
self.linthresh,
copy=False)
log = sign * self.linthresh * (
self._linscale_adj +
ma.log(np.abs(masked) / self.linthresh) / self._log_base)
if masked.mask.any():
return ma.where(masked.mask, a * self._linscale_adj, log)
else:
return log
def inverted(self):
3
Source : scale.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def transform_non_affine(self, a):
sign = np.sign(a)
masked = ma.masked_inside(a, -self.invlinthresh,
self.invlinthresh, copy=False)
exp = sign * self.linthresh * (
ma.power(self.base, (sign * (masked / self.linthresh))
- self._linscale_adj))
if masked.mask.any():
return ma.where(masked.mask, a / self._linscale_adj, exp)
else:
return exp
def inverted(self):
3
Source : atari_wrapper.py
with MIT License
from andi611
with MIT License
from andi611
def _reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
class WarpFrame(gym.ObservationWrapper):
3
Source : response.py
with GNU Affero General Public License v3.0
from andrewcooke
with GNU Affero General Public License v3.0
from andrewcooke
def calc_residuals(models, observations, method='L1'):
# -ve when observation less than model
if method == 'L1':
# use L1 scaled by amplitude to be reasonably robust.
return [(observation - model) / model.clip(lower=1e-6)
for model, observation in zip(models, observations)]
elif method == 'L2':
# something like chisq
return [(np.sign(observation - model) * (observation - model).pow(2) / model.clip(lower=1e-6))
for model, observation in zip(models, observations)]
else:
raise Exception(f'Unknown method ({method}) - use L1 or L2')
def calc_cost(model, observation, method='L1'):
3
Source : jaco_three_finger_gripper.py
with MIT License
from ARISE-Initiative
with MIT License
from ARISE-Initiative
def format_action(self, action):
"""
Maps continuous action into binary output
-1 => open, 1 => closed
Args:
action (np.array): gripper-specific action
Raises:
AssertionError: [Invalid action dimension size]
"""
assert len(action) == self.dof
self.current_action = np.clip(self.current_action - self.speed * np.sign(action), -1.0, 1.0)
return self.current_action
@property
3
Source : jaco_three_finger_gripper.py
with MIT License
from ARISE-Initiative
with MIT License
from ARISE-Initiative
def format_action(self, action):
"""
Maps continuous action into binary output
all -1 => open, all 1 => closed
Args:
action (np.array): gripper-specific action
Raises:
AssertionError: [Invalid action dimension size]
"""
assert len(action) == self.dof
self.current_action = np.clip(self.current_action - self.speed * np.sign(action), -1.0, 1.0)
return self.current_action
@property
3
Source : robotiq_85_gripper.py
with MIT License
from ARISE-Initiative
with MIT License
from ARISE-Initiative
def format_action(self, action):
"""
Maps continuous action into binary output
-1 => open, 1 => closed
Args:
action (np.array): gripper-specific action
Raises:
AssertionError: [Invalid action dimension size]
"""
assert len(action) == 1
self.current_action = np.clip(self.current_action + self.speed * np.sign(action), -1.0, 1.0)
return self.current_action
@property
3
Source : robotiq_three_finger_gripper.py
with MIT License
from ARISE-Initiative
with MIT License
from ARISE-Initiative
def format_action(self, action):
"""
Maps continuous action into binary output
all -1 => open, all 1 => closed
Args:
action (np.array): gripper-specific action
Raises:
AssertionError: [Invalid action dimension size]
"""
assert len(action) == self.dof
self.current_action = np.clip(self.current_action + self.speed * np.sign(action), -1.0, 1.0)
return self.current_action
@property
3
Source : Markov.py
with BSD 3-Clause "New" or "Revised" License
from aristoteleo
with BSD 3-Clause "New" or "Revised" License
from aristoteleo
def calc_Laplacian(E, convention="graph"):
A = np.abs(np.sign(E))
L = np.diag(np.sum(A, 0)) - A
if convention == "diffusion":
L = -L
return L
def fp_operator(E, D):
3
Source : exbasalganglia.py
with MIT License
from arnogranier
with MIT License
from arnogranier
def randomized_w(weight, size):
sign_w = np.sign(weight)
sigma_w = np.random.normal(0, 1, size=size)
w = abs(weight) + sigma_w * abs(weight)
w[w < 0] = 0
return sign_w * w
graph = tf.Graph()
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from arose13
with BSD 3-Clause "New" or "Revised" License
from arose13
def fit(self, X, y, check_input=True):
super(OLSL1, self).fit(X, y, check_input)
if self.ols_coefs:
self.coef_ = self.coef_ + np.sign(self.coef_) * self.alpha
# noinspection PyPep8Naming
class PreTrainedVoteEnsemble(ClassifierMixin):
3
Source : stats.py
with BSD 3-Clause "New" or "Revised" License
from arose13
with BSD 3-Clause "New" or "Revised" License
from arose13
def recover_ols_coef(coefs_ln, lam, method='l1'):
"""
Recovers the OLS estimate from regularisation methods
'Elements of Statistical Learning' (2009)
:param coefs_ln:
:param lam:
:param method:
:return:
"""
method = method.lower()
if method == 'l1':
return coefs_ln + np.sign(coefs_ln) * lam
elif method == 'l2':
return coefs_ln / (1 + lam)
def l1_coef_is_probably_correct(coefs: np.ndarray, x_fitted: np.ndarray, return_result=False):
3
Source : clip_reward.py
with MIT License
from artberryx
with MIT License
from artberryx
def step(self, ac):
"""gym.Env step function."""
obs, reward, done, info = self.env.step(ac)
return obs, np.sign(reward), done, info
def reset(self):
3
Source : cli.py
with MIT License
from ArthurBernard
with MIT License
from ArthurBernard
def _set_text_position(self):
txt_list = [['-'] * 6,
['Strategy', 'Real Position', 'Theorical Position', 'Rvol', 'Rvol2', 'Thvol'],
['-'] * 6]
for name, kwargs in self.strat_bot.items():
pnl = kwargs['pnl']
re_pos = pnl.position.iloc[0] + pnl.delta_signal.sum()
th_pos = kwargs['cpos']
re_vol = pnl.volume.iloc[0] + (pnl.PnL / pnl.price).sum()
re_vol_2 = pnl.volume.iloc[0] + (pnl.exchanged_volume * np.sign(pnl.delta_signal)).sum()
th_vol = kwargs['cvol']
txt_list += [[name, re_pos, th_pos, re_vol, re_vol_2, th_vol]]
return txt_list + [['-'] * 6]
if __name__ == "__main__":
3
Source : performance.py
with MIT License
from ArthurBernard
with MIT License
from ArthurBernard
def _get_slippage(self, price, d_signal, exch_vol, p_init):
return (p_init - price) * exch_vol * np.sign(d_signal)
class _FullPnL:
3
Source : storage_impl.py
with GNU General Public License v3.0
from atmos-cloud-sim-uj
with GNU General Public License v3.0
from atmos-cloud-sim-uj
def power(output, exponent):
# TODO #599 (was: output[:] = np.power(output, exponent))
output[:] = np.sign(output) * np.power(np.abs(output), exponent)
@numba.njit(**{**conf.JIT_FLAGS, **{"parallel": False}})
3
Source : _rgr.py
with MIT License
from AtrCheema
with MIT License
from AtrCheema
def mda(self) -> float:
""" Mean Directional Accuracy
modified after https://gist.github.com/bshishov/5dc237f59f019b26145648e2124ca1c9
"""
dict_acc = np.sign(self.true[1:] - self.true[:-1]) == np.sign(self.predicted[1:] - self.predicted[:-1])
return float(np.mean(dict_acc))
def mde(self) -> float:
3
Source : basis_execution_system.py
with Apache License 2.0
from Auquan
with Apache License 2.0
from Auquan
def hackCondition(self, currentPredictions, instrumentsManager):
instrumentLookbackData = instrumentsManager.getLookbackInstrumentFeatures()
position = pd.Series([instrumentsManager.getInstrument(x).getCurrentPosition() for x in instrumentsManager.getAllInstrumentsByInstrumentId()], index=instrumentsManager.getAllInstrumentsByInstrumentId())
avgEnterPrice = instrumentLookbackData.getFeatureDf('enter_price').iloc[-1]
hack = pd.Series(False, index=currentPredictions.index)
hack[np.sign(position)*(avgEnterPrice - currentPredictions)>0] = True
if instrumentLookbackData.getFeatureDf('position').index[-1].time() > self.hackTime :
hack[position!=0] = True
print('Hacking at Close......')
return hack
3
Source : simple_execution_system.py
with Apache License 2.0
from Auquan
with Apache License 2.0
from Auquan
def exitPosition(self, time, instrumentsManager, currentPredictions, closeAllPositions=False):
instrumentLookbackData = instrumentsManager.getLookbackInstrumentFeatures()
positionData = instrumentLookbackData.getFeatureDf('position')
position = positionData.iloc[-1]
price = self.getPriceSeries(instrumentsManager)
executions = pd.Series([0] * len(positionData.columns), index=positionData.columns)
if closeAllPositions:
executions = -position
return executions
executions[self.exitCondition(currentPredictions, instrumentsManager)] = -np.sign(position)*\
np.minimum(self.getExitLotSize(positionData.columns, price) , np.abs(position))
executions[self.hackCondition(currentPredictions, instrumentsManager)] = -np.sign(position)*\
np.minimum(self.getExitLotSize(positionData.columns, price) , np.abs(position))
return executions
def enterPosition(self, time, instrumentsManager, currentPredictions, capital):
3
Source : direction_feature.py
with Apache License 2.0
from Auquan
with Apache License 2.0
from Auquan
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
dataDf = instrumentLookbackData.getFeatureDf(featureParams['featureName'])
if len(dataDf.index) < featureParams['period']:
instrumentDict = instrumentManager.getAllInstrumentsByInstrumentId()
zeroSeries = pd.Series([0] * len(instrumentDict), index=instrumentDict.keys())
return zeroSeries
return np.sign(dataDf.iloc[-1] - dataDf.iloc[-featureParams['period']])
@classmethod
3
Source : direction_feature.py
with Apache License 2.0
from Auquan
with Apache License 2.0
from Auquan
def computeForMarket(cls, updateNum, time, featureParams, featureKey, currentMarketFeatures, instrumentManager):
lookbackDataDf = instrumentManager.getDataDf()
data = lookbackDataDf[featureParams['featureName']]
if len(data.index) < featureParams['period']:
return 0
return np.sign(data[-1] - data[-featureParams['period']])
3
Source : action_states.py
with GNU General Public License v3.0
from b-it-bots
with GNU General Public License v3.0
from b-it-bots
def __move_base_along_x(self, distance_to_move):
'''Sends a MoveForwardGoal to move the base for the given distance.
The call is non-blocking, i.e. the function returns immediately after
sending the goal without waiting for the action to complete.
'''
movement_speed = np.sign(distance_to_move) * 0.1 # m/s
movement_duration = distance_to_move / movement_speed
move_forward_goal = MoveForwardGoal()
move_forward_goal.movement_duration = movement_duration
move_forward_goal.speed = movement_speed
self.move_forward_client.send_goal(move_forward_goal)
def recovering(self):
3
Source : action_states.py
with GNU General Public License v3.0
from b-it-bots
with GNU General Public License v3.0
from b-it-bots
def __move_base_along_x(self, distance_to_move):
movement_speed = np.sign(distance_to_move) * 0.1 # m/s
movement_duration = distance_to_move / movement_speed
move_forward_goal = MoveForwardGoal()
move_forward_goal.movement_duration = movement_duration
move_forward_goal.speed = movement_speed
self.move_forward_client.send_goal(move_forward_goal)
self.move_forward_client.wait_for_result()
self.move_forward_client.get_result()
def set_result(self, success):
3
Source : feature_extraction.py
with MIT License
from B05901022
with MIT License
from B05901022
def findpeaks(x, th):
# x is an input column vector
M = x.shape[0]
pre = x[1:M - 1] - x[0:M - 2]
pre = np.sign(pre)
post = x[1:M - 1] - x[2:]
post = np.sign(post)
mask = pre * post
ext_mask = np.pad(mask,1)
locs = np.where(ext_mask==1)
locs = locs[0]
return locs
def melody_extraction(audio, batch_size, num_workers, pin_memory, device):
3
Source : deep_lesion_dataset.py
with Apache License 2.0
from baidu-research
with Apache License 2.0
from baidu-research
def make_path(self, sub_path, slice_idx, delta):
while not os.path.exists(
os.path.join(self._cfg['DATAPATH'], 'Images_png', sub_path,
str(slice_idx + delta).zfill(3) + '.png')):
delta -= np.sign(delta)
if delta == 0:
break
return os.path.join(self._cfg['DATAPATH'], 'Images_png', sub_path,
str(slice_idx + delta).zfill(3) + '.png')
def load_img(self, idx):
3
Source : geometry.py
with BSD 3-Clause "New" or "Revised" License
from bdd100k
with BSD 3-Clause "New" or "Revised" License
from bdd100k
def check_side_of_line(point, line):
p1, p2 = line
det = (point[0] - p1[0]) * (p2[1] - p1[1]) - (point[1] - p1[1]) * (
p2[0] - p1[0]
)
return np.sign(det)
def check_clockwise(points):
See More Examples