id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
12,538 | import torch
from im2mesh.utils.libkdtree import KDTree
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `compute_iou` function. Write a Python function `def compute_iou(occ1, occ2)` to solve the following problem:
Computes the Intersection over Union (IoU) value for two sets of occupancy values. Args: occ1 (tensor): first set of occupancy values occ2 (tensor): second set of occupancy values
Here is the function:
def compute_iou(occ1, occ2):
''' Computes the Intersection over Union (IoU) value for two sets of
occupancy values.
Args:
occ1 (tensor): first set of occupancy values
occ2 (tensor): second set of occupancy values
'''
occ1 = np.asarray(occ1)
occ2 = np.asarray(occ2)
# Put all data in second dimension
# Also works for 1-dimensional data
if occ1.ndim >= 2:
occ1 = occ1.reshape(occ1.shape[0], -1)
if occ2.ndim >= 2:
occ2 = occ2.reshape(occ2.shape[0], -1)
# Convert to boolean values
occ1 = (occ1 >= 0.5)
occ2 = (occ2 >= 0.5)
# Compute IOU
area_union = (occ1 | occ2).astype(np.float32).sum(axis=-1)
area_intersect = (occ1 & occ2).astype(np.float32).sum(axis=-1)
iou = (area_intersect / area_union)
return iou | Computes the Intersection over Union (IoU) value for two sets of occupancy values. Args: occ1 (tensor): first set of occupancy values occ2 (tensor): second set of occupancy values |
12,539 | import torch
from im2mesh.utils.libkdtree import KDTree
import numpy as np
def chamfer_distance_naive(points1, points2):
''' Naive implementation of the Chamfer distance.
Args:
points1 (numpy array): first point set
points2 (numpy array): second point set
'''
assert(points1.size() == points2.size())
batch_size, T, _ = points1.size()
points1 = points1.view(batch_size, T, 1, 3)
points2 = points2.view(batch_size, 1, T, 3)
distances = (points1 - points2).pow(2).sum(-1)
chamfer1 = distances.min(dim=1)[0].mean(dim=1)
chamfer2 = distances.min(dim=2)[0].mean(dim=1)
chamfer = chamfer1 + chamfer2
return chamfer
def chamfer_distance_kdtree(points1, points2, give_id=False):
''' KD-tree based implementation of the Chamfer distance.
Args:
points1 (numpy array): first point set
points2 (numpy array): second point set
give_id (bool): whether to return the IDs of the nearest points
'''
# Points have size batch_size x T x 3
batch_size = points1.size(0)
# First convert points to numpy
points1_np = points1.detach().cpu().numpy()
points2_np = points2.detach().cpu().numpy()
# Get list of nearest neighbors indieces
idx_nn_12, _ = get_nearest_neighbors_indices_batch(points1_np, points2_np)
idx_nn_12 = torch.LongTensor(idx_nn_12).to(points1.device)
# Expands it as batch_size x 1 x 3
idx_nn_12_expand = idx_nn_12.view(batch_size, -1, 1).expand_as(points1)
# Get list of nearest neighbors indieces
idx_nn_21, _ = get_nearest_neighbors_indices_batch(points2_np, points1_np)
idx_nn_21 = torch.LongTensor(idx_nn_21).to(points1.device)
# Expands it as batch_size x T x 3
idx_nn_21_expand = idx_nn_21.view(batch_size, -1, 1).expand_as(points2)
# Compute nearest neighbors in points2 to points in points1
# points_12[i, j, k] = points2[i, idx_nn_12_expand[i, j, k], k]
points_12 = torch.gather(points2, dim=1, index=idx_nn_12_expand)
# Compute nearest neighbors in points1 to points in points2
# points_21[i, j, k] = points2[i, idx_nn_21_expand[i, j, k], k]
points_21 = torch.gather(points1, dim=1, index=idx_nn_21_expand)
# Compute chamfer distance
chamfer1 = (points1 - points_12).pow(2).sum(2).mean(1)
chamfer2 = (points2 - points_21).pow(2).sum(2).mean(1)
# Take sum
chamfer = chamfer1 + chamfer2
# If required, also return nearest neighbors
if give_id:
return chamfer1, chamfer2, idx_nn_12, idx_nn_21
return chamfer
The provided code snippet includes necessary dependencies for implementing the `chamfer_distance` function. Write a Python function `def chamfer_distance(points1, points2, use_kdtree=True, give_id=False)` to solve the following problem:
Returns the chamfer distance for the sets of points. Args: points1 (numpy array): first point set points2 (numpy array): second point set use_kdtree (bool): whether to use a kdtree give_id (bool): whether to return the IDs of nearest points
Here is the function:
def chamfer_distance(points1, points2, use_kdtree=True, give_id=False):
''' Returns the chamfer distance for the sets of points.
Args:
points1 (numpy array): first point set
points2 (numpy array): second point set
use_kdtree (bool): whether to use a kdtree
give_id (bool): whether to return the IDs of nearest points
'''
if use_kdtree:
return chamfer_distance_kdtree(points1, points2, give_id=give_id)
else:
return chamfer_distance_naive(points1, points2) | Returns the chamfer distance for the sets of points. Args: points1 (numpy array): first point set points2 (numpy array): second point set use_kdtree (bool): whether to use a kdtree give_id (bool): whether to return the IDs of nearest points |
12,540 | import torch
from im2mesh.utils.libkdtree import KDTree
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `normalize_imagenet` function. Write a Python function `def normalize_imagenet(x)` to solve the following problem:
Normalize input images according to ImageNet standards. Args: x (tensor): input images
Here is the function:
def normalize_imagenet(x):
''' Normalize input images according to ImageNet standards.
Args:
x (tensor): input images
'''
x = x.clone()
x[:, 0] = (x[:, 0] - 0.485) / 0.229
x[:, 1] = (x[:, 1] - 0.456) / 0.224
x[:, 2] = (x[:, 2] - 0.406) / 0.225
return x | Normalize input images according to ImageNet standards. Args: x (tensor): input images |
12,541 | import torch
from im2mesh.utils.libkdtree import KDTree
import numpy as np
def b_inv(b_mat):
''' Performs batch matrix inversion.
Arguments:
b_mat: the batch of matrices that should be inverted
'''
eye = b_mat.new_ones(b_mat.size(-1)).diag().expand_as(b_mat)
b_inv, _ = torch.gesv(eye, b_mat)
return b_inv
The provided code snippet includes necessary dependencies for implementing the `transform_points_back` function. Write a Python function `def transform_points_back(points, transform)` to solve the following problem:
Inverts the transformation. Args: points (tensor): points tensor transform (tensor): transformation matrices
Here is the function:
def transform_points_back(points, transform):
''' Inverts the transformation.
Args:
points (tensor): points tensor
transform (tensor): transformation matrices
'''
assert(points.size(2) == 3)
assert(transform.size(1) == 3)
assert(points.size(0) == transform.size(0))
if transform.size(2) == 4:
R = transform[:, :, :3]
t = transform[:, :, 3:]
points_out = points - t.transpose(1, 2)
points_out = points_out @ b_inv(R.transpose(1, 2))
elif transform.size(2) == 3:
K = transform
points_out = points @ b_inv(K.transpose(1, 2))
return points_out | Inverts the transformation. Args: points (tensor): points tensor transform (tensor): transformation matrices |
12,542 | import torch
from im2mesh.utils.libkdtree import KDTree
import numpy as np
def fix_Rt_camera(Rt, loc, scale):
''' Fixes Rt camera matrix.
Args:
Rt (tensor): Rt camera matrix
loc (tensor): location
scale (float): scale
'''
# Rt is B x 3 x 4
# loc is B x 3 and scale is B
batch_size = Rt.size(0)
R = Rt[:, :, :3]
t = Rt[:, :, 3:]
scale = scale.view(batch_size, 1, 1)
R_new = R * scale
t_new = t + R @ loc.unsqueeze(2)
Rt_new = torch.cat([R_new, t_new], dim=2)
assert(Rt_new.size() == (batch_size, 3, 4))
return Rt_new
def fix_K_camera(K, img_size=137):
"""Fix camera projection matrix.
This changes a camera projection matrix that maps to
[0, img_size] x [0, img_size] to one that maps to [-1, 1] x [-1, 1].
Args:
K (np.ndarray): Camera projection matrix.
img_size (float): Size of image plane K projects to.
"""
# Unscale and recenter
scale_mat = torch.tensor([
[2./img_size, 0, -1],
[0, 2./img_size, -1],
[0, 0, 1.],
], device=K.device, dtype=K.dtype)
K_new = scale_mat.view(1, 3, 3) @ K
return K_new
The provided code snippet includes necessary dependencies for implementing the `get_camera_args` function. Write a Python function `def get_camera_args(data, loc_field=None, scale_field=None, device=None)` to solve the following problem:
Returns dictionary of camera arguments. Args: data (dict): data dictionary loc_field (str): name of location field scale_field (str): name of scale field device (device): pytorch device
Here is the function:
def get_camera_args(data, loc_field=None, scale_field=None, device=None):
''' Returns dictionary of camera arguments.
Args:
data (dict): data dictionary
loc_field (str): name of location field
scale_field (str): name of scale field
device (device): pytorch device
'''
Rt = data['inputs.world_mat'].to(device)
K = data['inputs.camera_mat'].to(device)
if loc_field is not None:
loc = data[loc_field].to(device)
else:
loc = torch.zeros(K.size(0), 3, device=K.device, dtype=K.dtype)
if scale_field is not None:
scale = data[scale_field].to(device)
else:
scale = torch.zeros(K.size(0), device=K.device, dtype=K.dtype)
Rt = fix_Rt_camera(Rt, loc, scale)
K = fix_K_camera(K, img_size=137.)
kwargs = {'Rt': Rt, 'K': K}
return kwargs | Returns dictionary of camera arguments. Args: data (dict): data dictionary loc_field (str): name of location field scale_field (str): name of scale field device (device): pytorch device |
12,543 | import logging
import numpy as np
import trimesh
from im2mesh.utils.libkdtree import KDTree
from im2mesh.utils.libmesh import check_mesh_contains
from im2mesh.common import compute_iou
The provided code snippet includes necessary dependencies for implementing the `distance_p2p` function. Write a Python function `def distance_p2p(points_src, normals_src, points_tgt, normals_tgt)` to solve the following problem:
Computes minimal distances of each point in points_src to points_tgt. Args: points_src (numpy array): source points normals_src (numpy array): source normals points_tgt (numpy array): target points normals_tgt (numpy array): target normals
Here is the function:
def distance_p2p(points_src, normals_src, points_tgt, normals_tgt):
''' Computes minimal distances of each point in points_src to points_tgt.
Args:
points_src (numpy array): source points
normals_src (numpy array): source normals
points_tgt (numpy array): target points
normals_tgt (numpy array): target normals
'''
kdtree = KDTree(points_tgt)
dist, idx = kdtree.query(points_src)
if normals_src is not None and normals_tgt is not None:
normals_src = \
normals_src / np.linalg.norm(normals_src, axis=-1, keepdims=True)
normals_tgt = \
normals_tgt / np.linalg.norm(normals_tgt, axis=-1, keepdims=True)
normals_dot_product = (normals_tgt[idx] * normals_src).sum(axis=-1)
# Handle normals that point into wrong direction gracefully
# (mostly due to mehtod not caring about this in generation)
normals_dot_product = np.abs(normals_dot_product)
else:
normals_dot_product = np.array(
[np.nan] * points_src.shape[0], dtype=np.float32)
return dist, normals_dot_product | Computes minimal distances of each point in points_src to points_tgt. Args: points_src (numpy array): source points normals_src (numpy array): source normals points_tgt (numpy array): target points normals_tgt (numpy array): target normals |
12,544 | import logging
import numpy as np
import trimesh
from im2mesh.utils.libkdtree import KDTree
from im2mesh.utils.libmesh import check_mesh_contains
from im2mesh.common import compute_iou
The provided code snippet includes necessary dependencies for implementing the `distance_p2m` function. Write a Python function `def distance_p2m(points, mesh)` to solve the following problem:
Compute minimal distances of each point in points to mesh. Args: points (numpy array): points array mesh (trimesh): mesh
Here is the function:
def distance_p2m(points, mesh):
''' Compute minimal distances of each point in points to mesh.
Args:
points (numpy array): points array
mesh (trimesh): mesh
'''
_, dist, _ = trimesh.proximity.closest_point(mesh, points)
return dist | Compute minimal distances of each point in points to mesh. Args: points (numpy array): points array mesh (trimesh): mesh |
12,545 | import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from torchvision.utils import save_image
import im2mesh.common as common
def visualize_voxels(voxels, out_file=None, show=False):
r''' Visualizes voxel data.
Args:
voxels (tensor): voxel data
out_file (string): output file
show (bool): whether the plot should be shown
'''
# Use numpy
voxels = np.asarray(voxels)
# Create plot
fig = plt.figure()
ax = fig.gca(projection=Axes3D.name)
voxels = voxels.transpose(2, 0, 1)
ax.voxels(voxels, edgecolor='k')
ax.set_xlabel('Z')
ax.set_ylabel('X')
ax.set_zlabel('Y')
ax.view_init(elev=30, azim=45)
if out_file is not None:
plt.savefig(out_file)
if show:
plt.show()
plt.close(fig)
def visualize_pointcloud(points, normals=None,
out_file=None, show=False):
r''' Visualizes point cloud data.
Args:
points (tensor): point data
normals (tensor): normal data (if existing)
out_file (string): output file
show (bool): whether the plot should be shown
'''
# Use numpy
points = np.asarray(points)
# Create plot
fig = plt.figure()
ax = fig.gca(projection=Axes3D.name)
ax.scatter(points[:, 2], points[:, 0], points[:, 1])
if normals is not None:
ax.quiver(
points[:, 2], points[:, 0], points[:, 1],
normals[:, 2], normals[:, 0], normals[:, 1],
length=0.1, color='k'
)
ax.set_xlabel('Z')
ax.set_ylabel('X')
ax.set_zlabel('Y')
ax.set_xlim(-0.5, 0.5)
ax.set_ylim(-0.5, 0.5)
ax.set_zlim(-0.5, 0.5)
ax.view_init(elev=30, azim=45)
if out_file is not None:
plt.savefig(out_file)
if show:
plt.show()
plt.close(fig)
The provided code snippet includes necessary dependencies for implementing the `visualize_data` function. Write a Python function `def visualize_data(data, data_type, out_file)` to solve the following problem:
r''' Visualizes the data with regard to its type. Args: data (tensor): batch of data data_type (string): data type (img, voxels or pointcloud) out_file (string): output file
Here is the function:
def visualize_data(data, data_type, out_file):
r''' Visualizes the data with regard to its type.
Args:
data (tensor): batch of data
data_type (string): data type (img, voxels or pointcloud)
out_file (string): output file
'''
if data_type == 'img':
if data.dim() == 3:
data = data.unsqueeze(0)
save_image(data, out_file, nrow=4)
elif data_type == 'voxels':
visualize_voxels(data, out_file=out_file)
elif data_type == 'pointcloud':
visualize_pointcloud(data, out_file=out_file)
elif data_type is None or data_type == 'idx':
pass
else:
raise ValueError('Invalid data_type "%s"' % data_type) | r''' Visualizes the data with regard to its type. Args: data (tensor): batch of data data_type (string): data type (img, voxels or pointcloud) out_file (string): output file |
12,546 | import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from torchvision.utils import save_image
import im2mesh.common as common
The provided code snippet includes necessary dependencies for implementing the `visualise_projection` function. Write a Python function `def visualise_projection( self, points, world_mat, camera_mat, img, output_file='out.png')` to solve the following problem:
r''' Visualizes the transformation and projection to image plane. The first points of the batch are transformed and projected to the respective image. After performing the relevant transformations, the visualization is saved in the provided output_file path. Arguments: points (tensor): batch of point cloud points world_mat (tensor): batch of matrices to rotate pc to camera-based coordinates camera_mat (tensor): batch of camera matrices to project to 2D image plane img (tensor): tensor of batch GT image files output_file (string): where the output should be saved
Here is the function:
def visualise_projection(
self, points, world_mat, camera_mat, img, output_file='out.png'):
r''' Visualizes the transformation and projection to image plane.
The first points of the batch are transformed and projected to the
respective image. After performing the relevant transformations, the
visualization is saved in the provided output_file path.
Arguments:
points (tensor): batch of point cloud points
world_mat (tensor): batch of matrices to rotate pc to camera-based
coordinates
camera_mat (tensor): batch of camera matrices to project to 2D image
plane
img (tensor): tensor of batch GT image files
output_file (string): where the output should be saved
'''
points_transformed = common.transform_points(points, world_mat)
points_img = common.project_to_camera(points_transformed, camera_mat)
pimg2 = points_img[0].detach().cpu().numpy()
image = img[0].cpu().numpy()
plt.imshow(image.transpose(1, 2, 0))
plt.plot(
(pimg2[:, 0] + 1)*image.shape[1]/2,
(pimg2[:, 1] + 1) * image.shape[2]/2, 'x')
plt.savefig(output_file) | r''' Visualizes the transformation and projection to image plane. The first points of the batch are transformed and projected to the respective image. After performing the relevant transformations, the visualization is saved in the provided output_file path. Arguments: points (tensor): batch of point cloud points world_mat (tensor): batch of matrices to rotate pc to camera-based coordinates camera_mat (tensor): batch of camera matrices to project to 2D image plane img (tensor): tensor of batch GT image files output_file (string): where the output should be saved |
12,547 | import numpy as np
import trimesh
from scipy import ndimage
from skimage.measure import block_reduce
from im2mesh.utils.libvoxelize.voxelize import voxelize_mesh_
from im2mesh.utils.libmesh import check_mesh_contains
from im2mesh.common import make_3d_grid
def voxelize_surface(mesh, resolution):
vertices = mesh.vertices
faces = mesh.faces
vertices = (vertices + 0.5) * resolution
face_loc = vertices[faces]
occ = np.full((resolution,) * 3, 0, dtype=np.int32)
face_loc = face_loc.astype(np.float32)
voxelize_mesh_(occ, face_loc)
occ = (occ != 0)
return occ
def voxelize_interior(mesh, resolution):
shape = (resolution,) * 3
bb_min = (0.5,) * 3
bb_max = (resolution - 0.5,) * 3
# Create points. Add noise to break symmetry
points = make_3d_grid(bb_min, bb_max, shape=shape).numpy()
points = points + 0.1 * (np.random.rand(*points.shape) - 0.5)
points = (points / resolution - 0.5)
occ = check_mesh_contains(mesh, points)
occ = occ.reshape(shape)
return occ
def voxelize_ray(mesh, resolution):
occ_surface = voxelize_surface(mesh, resolution)
# TODO: use surface voxels here?
occ_interior = voxelize_interior(mesh, resolution)
occ = (occ_interior | occ_surface)
return occ | null |
12,548 | import numpy as np
import trimesh
from scipy import ndimage
from skimage.measure import block_reduce
from im2mesh.utils.libvoxelize.voxelize import voxelize_mesh_
from im2mesh.utils.libmesh import check_mesh_contains
from im2mesh.common import make_3d_grid
def voxelize_surface(mesh, resolution):
vertices = mesh.vertices
faces = mesh.faces
vertices = (vertices + 0.5) * resolution
face_loc = vertices[faces]
occ = np.full((resolution,) * 3, 0, dtype=np.int32)
face_loc = face_loc.astype(np.float32)
voxelize_mesh_(occ, face_loc)
occ = (occ != 0)
return occ
def voxelize_fill(mesh, resolution):
bounds = mesh.bounds
if (np.abs(bounds) >= 0.5).any():
raise ValueError('voxelize fill is only supported if mesh is inside [-0.5, 0.5]^3/')
occ = voxelize_surface(mesh, resolution)
occ = ndimage.morphology.binary_fill_holes(occ)
return occ | null |
12,549 | import numpy as np
import trimesh
from scipy import ndimage
from skimage.measure import block_reduce
from im2mesh.utils.libvoxelize.voxelize import voxelize_mesh_
from im2mesh.utils.libmesh import check_mesh_contains
from im2mesh.common import make_3d_grid
def check_voxel_occupied(occupancy_grid):
occ = occupancy_grid
occupied = (
occ[..., :-1, :-1, :-1]
& occ[..., :-1, :-1, 1:]
& occ[..., :-1, 1:, :-1]
& occ[..., :-1, 1:, 1:]
& occ[..., 1:, :-1, :-1]
& occ[..., 1:, :-1, 1:]
& occ[..., 1:, 1:, :-1]
& occ[..., 1:, 1:, 1:]
)
return occupied
def check_voxel_unoccupied(occupancy_grid):
occ = occupancy_grid
unoccupied = ~(
occ[..., :-1, :-1, :-1]
| occ[..., :-1, :-1, 1:]
| occ[..., :-1, 1:, :-1]
| occ[..., :-1, 1:, 1:]
| occ[..., 1:, :-1, :-1]
| occ[..., 1:, :-1, 1:]
| occ[..., 1:, 1:, :-1]
| occ[..., 1:, 1:, 1:]
)
return unoccupied
def check_voxel_boundary(occupancy_grid):
occupied = check_voxel_occupied(occupancy_grid)
unoccupied = check_voxel_unoccupied(occupancy_grid)
return ~occupied & ~unoccupied | null |
12,550 | import numpy as np
class Voxels(object):
""" Holds a binvox model.
data is either a three-dimensional numpy boolean array (dense representation)
or a two-dimensional numpy float array (coordinate representation).
dims, translate and scale are the model metadata.
dims are the voxel dimensions, e.g. [32, 32, 32] for a 32x32x32 model.
scale and translate relate the voxels to the original model coordinates.
To translate voxel coordinates i, j, k to original coordinates x, y, z:
x_n = (i+.5)/dims[0]
y_n = (j+.5)/dims[1]
z_n = (k+.5)/dims[2]
x = scale*x_n + translate[0]
y = scale*y_n + translate[1]
z = scale*z_n + translate[2]
"""
def __init__(self, data, dims, translate, scale, axis_order):
self.data = data
self.dims = dims
self.translate = translate
self.scale = scale
assert (axis_order in ('xzy', 'xyz'))
self.axis_order = axis_order
def clone(self):
data = self.data.copy()
dims = self.dims[:]
translate = self.translate[:]
return Voxels(data, dims, translate, self.scale, self.axis_order)
def write(self, fp):
write(self, fp)
def read_header(fp):
""" Read binvox header. Mostly meant for internal use.
"""
line = fp.readline().strip()
if not line.startswith(b'#binvox'):
raise IOError('Not a binvox file')
dims = [int(i) for i in fp.readline().strip().split(b' ')[1:]]
translate = [float(i) for i in fp.readline().strip().split(b' ')[1:]]
scale = [float(i) for i in fp.readline().strip().split(b' ')[1:]][0]
line = fp.readline()
return dims, translate, scale
The provided code snippet includes necessary dependencies for implementing the `read_as_3d_array` function. Write a Python function `def read_as_3d_array(fp, fix_coords=True)` to solve the following problem:
Read binary binvox format as array. Returns the model with accompanying metadata. Voxels are stored in a three-dimensional numpy array, which is simple and direct, but may use a lot of memory for large models. (Storage requirements are 8*(d^3) bytes, where d is the dimensions of the binvox model. Numpy boolean arrays use a byte per element). Doesn't do any checks on input except for the '#binvox' line.
Here is the function:
def read_as_3d_array(fp, fix_coords=True):
""" Read binary binvox format as array.
Returns the model with accompanying metadata.
Voxels are stored in a three-dimensional numpy array, which is simple and
direct, but may use a lot of memory for large models. (Storage requirements
are 8*(d^3) bytes, where d is the dimensions of the binvox model. Numpy
boolean arrays use a byte per element).
Doesn't do any checks on input except for the '#binvox' line.
"""
dims, translate, scale = read_header(fp)
raw_data = np.frombuffer(fp.read(), dtype=np.uint8)
# if just using reshape() on the raw data:
# indexing the array as array[i,j,k], the indices map into the
# coords as:
# i -> x
# j -> z
# k -> y
# if fix_coords is true, then data is rearranged so that
# mapping is
# i -> x
# j -> y
# k -> z
values, counts = raw_data[::2], raw_data[1::2]
data = np.repeat(values, counts).astype(np.bool)
data = data.reshape(dims)
if fix_coords:
# xzy to xyz TODO the right thing
data = np.transpose(data, (0, 2, 1))
axis_order = 'xyz'
else:
axis_order = 'xzy'
return Voxels(data, dims, translate, scale, axis_order) | Read binary binvox format as array. Returns the model with accompanying metadata. Voxels are stored in a three-dimensional numpy array, which is simple and direct, but may use a lot of memory for large models. (Storage requirements are 8*(d^3) bytes, where d is the dimensions of the binvox model. Numpy boolean arrays use a byte per element). Doesn't do any checks on input except for the '#binvox' line. |
12,551 | import numpy as np
class Voxels(object):
""" Holds a binvox model.
data is either a three-dimensional numpy boolean array (dense representation)
or a two-dimensional numpy float array (coordinate representation).
dims, translate and scale are the model metadata.
dims are the voxel dimensions, e.g. [32, 32, 32] for a 32x32x32 model.
scale and translate relate the voxels to the original model coordinates.
To translate voxel coordinates i, j, k to original coordinates x, y, z:
x_n = (i+.5)/dims[0]
y_n = (j+.5)/dims[1]
z_n = (k+.5)/dims[2]
x = scale*x_n + translate[0]
y = scale*y_n + translate[1]
z = scale*z_n + translate[2]
"""
def __init__(self, data, dims, translate, scale, axis_order):
self.data = data
self.dims = dims
self.translate = translate
self.scale = scale
assert (axis_order in ('xzy', 'xyz'))
self.axis_order = axis_order
def clone(self):
data = self.data.copy()
dims = self.dims[:]
translate = self.translate[:]
return Voxels(data, dims, translate, self.scale, self.axis_order)
def write(self, fp):
write(self, fp)
def read_header(fp):
""" Read binvox header. Mostly meant for internal use.
"""
line = fp.readline().strip()
if not line.startswith(b'#binvox'):
raise IOError('Not a binvox file')
dims = [int(i) for i in fp.readline().strip().split(b' ')[1:]]
translate = [float(i) for i in fp.readline().strip().split(b' ')[1:]]
scale = [float(i) for i in fp.readline().strip().split(b' ')[1:]][0]
line = fp.readline()
return dims, translate, scale
The provided code snippet includes necessary dependencies for implementing the `read_as_coord_array` function. Write a Python function `def read_as_coord_array(fp, fix_coords=True)` to solve the following problem:
Read binary binvox format as coordinates. Returns binvox model with voxels in a "coordinate" representation, i.e. an 3 x N array where N is the number of nonzero voxels. Each column corresponds to a nonzero voxel and the 3 rows are the (x, z, y) coordinates of the voxel. (The odd ordering is due to the way binvox format lays out data). Note that coordinates refer to the binvox voxels, without any scaling or translation. Use this to save memory if your model is very sparse (mostly empty). Doesn't do any checks on input except for the '#binvox' line.
Here is the function:
def read_as_coord_array(fp, fix_coords=True):
""" Read binary binvox format as coordinates.
Returns binvox model with voxels in a "coordinate" representation, i.e. an
3 x N array where N is the number of nonzero voxels. Each column
corresponds to a nonzero voxel and the 3 rows are the (x, z, y) coordinates
of the voxel. (The odd ordering is due to the way binvox format lays out
data). Note that coordinates refer to the binvox voxels, without any
scaling or translation.
Use this to save memory if your model is very sparse (mostly empty).
Doesn't do any checks on input except for the '#binvox' line.
"""
dims, translate, scale = read_header(fp)
raw_data = np.frombuffer(fp.read(), dtype=np.uint8)
values, counts = raw_data[::2], raw_data[1::2]
sz = np.prod(dims)
index, end_index = 0, 0
end_indices = np.cumsum(counts)
indices = np.concatenate(([0], end_indices[:-1])).astype(end_indices.dtype)
values = values.astype(np.bool)
indices = indices[values]
end_indices = end_indices[values]
nz_voxels = []
for index, end_index in zip(indices, end_indices):
nz_voxels.extend(range(index, end_index))
nz_voxels = np.array(nz_voxels)
# TODO are these dims correct?
# according to docs,
# index = x * wxh + z * width + y; // wxh = width * height = d * d
x = nz_voxels / (dims[0]*dims[1])
zwpy = nz_voxels % (dims[0]*dims[1]) # z*w + y
z = zwpy / dims[0]
y = zwpy % dims[0]
if fix_coords:
data = np.vstack((x, y, z))
axis_order = 'xyz'
else:
data = np.vstack((x, z, y))
axis_order = 'xzy'
#return Voxels(data, dims, translate, scale, axis_order)
return Voxels(np.ascontiguousarray(data), dims, translate, scale, axis_order) | Read binary binvox format as coordinates. Returns binvox model with voxels in a "coordinate" representation, i.e. an 3 x N array where N is the number of nonzero voxels. Each column corresponds to a nonzero voxel and the 3 rows are the (x, z, y) coordinates of the voxel. (The odd ordering is due to the way binvox format lays out data). Note that coordinates refer to the binvox voxels, without any scaling or translation. Use this to save memory if your model is very sparse (mostly empty). Doesn't do any checks on input except for the '#binvox' line. |
12,552 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `dense_to_sparse` function. Write a Python function `def dense_to_sparse(voxel_data, dtype=np.int)` to solve the following problem:
From dense representation to sparse (coordinate) representation. No coordinate reordering.
Here is the function:
def dense_to_sparse(voxel_data, dtype=np.int):
""" From dense representation to sparse (coordinate) representation.
No coordinate reordering.
"""
if voxel_data.ndim!=3:
raise ValueError('voxel_data is wrong shape; should be 3D array.')
return np.asarray(np.nonzero(voxel_data), dtype) | From dense representation to sparse (coordinate) representation. No coordinate reordering. |
12,553 | import numpy as np
from sklearn.neighbors import NearestNeighbors
def best_fit_transform(A, B):
'''
Calculates the least-squares best-fit transform that maps corresponding
points A to B in m spatial dimensions
Input:
A: Nxm numpy array of corresponding points
B: Nxm numpy array of corresponding points
Returns:
T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B
R: mxm rotation matrix
t: mx1 translation vector
'''
assert A.shape == B.shape
# get number of dimensions
m = A.shape[1]
# translate points to their centroids
centroid_A = np.mean(A, axis=0)
centroid_B = np.mean(B, axis=0)
AA = A - centroid_A
BB = B - centroid_B
# rotation matrix
H = np.dot(AA.T, BB)
U, S, Vt = np.linalg.svd(H)
R = np.dot(Vt.T, U.T)
# special reflection case
if np.linalg.det(R) < 0:
Vt[m-1,:] *= -1
R = np.dot(Vt.T, U.T)
# translation
t = centroid_B.T - np.dot(R,centroid_A.T)
# homogeneous transformation
T = np.identity(m+1)
T[:m, :m] = R
T[:m, m] = t
return T, R, t
def nearest_neighbor(src, dst):
'''
Find the nearest (Euclidean) neighbor in dst for each point in src
Input:
src: Nxm array of points
dst: Nxm array of points
Output:
distances: Euclidean distances of the nearest neighbor
indices: dst indices of the nearest neighbor
'''
assert src.shape == dst.shape
neigh = NearestNeighbors(n_neighbors=1)
neigh.fit(dst)
distances, indices = neigh.kneighbors(src, return_distance=True)
return distances.ravel(), indices.ravel()
The provided code snippet includes necessary dependencies for implementing the `icp` function. Write a Python function `def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001)` to solve the following problem:
The Iterative Closest Point method: finds best-fit transform that maps points A on to points B Input: A: Nxm numpy array of source mD points B: Nxm numpy array of destination mD point init_pose: (m+1)x(m+1) homogeneous transformation max_iterations: exit algorithm after max_iterations tolerance: convergence criteria Output: T: final homogeneous transformation that maps A on to B distances: Euclidean distances (errors) of the nearest neighbor i: number of iterations to converge
Here is the function:
def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001):
'''
The Iterative Closest Point method: finds best-fit transform that maps
points A on to points B
Input:
A: Nxm numpy array of source mD points
B: Nxm numpy array of destination mD point
init_pose: (m+1)x(m+1) homogeneous transformation
max_iterations: exit algorithm after max_iterations
tolerance: convergence criteria
Output:
T: final homogeneous transformation that maps A on to B
distances: Euclidean distances (errors) of the nearest neighbor
i: number of iterations to converge
'''
assert A.shape == B.shape
# get number of dimensions
m = A.shape[1]
# make points homogeneous, copy them to maintain the originals
src = np.ones((m+1,A.shape[0]))
dst = np.ones((m+1,B.shape[0]))
src[:m,:] = np.copy(A.T)
dst[:m,:] = np.copy(B.T)
# apply the initial pose estimation
if init_pose is not None:
src = np.dot(init_pose, src)
prev_error = 0
for i in range(max_iterations):
# find the nearest neighbors between the current source and destination points
distances, indices = nearest_neighbor(src[:m,:].T, dst[:m,:].T)
# compute the transformation between the current source and nearest destination points
T,_,_ = best_fit_transform(src[:m,:].T, dst[:m,indices].T)
# update the current source
src = np.dot(T, src)
# check error
mean_error = np.mean(distances)
if np.abs(prev_error - mean_error) < tolerance:
break
prev_error = mean_error
# calculate final transformation
T,_,_ = best_fit_transform(A, src[:m,:].T)
return T, distances, i | The Iterative Closest Point method: finds best-fit transform that maps points A on to points B Input: A: Nxm numpy array of source mD points B: Nxm numpy array of destination mD point init_pose: (m+1)x(m+1) homogeneous transformation max_iterations: exit algorithm after max_iterations tolerance: convergence criteria Output: T: final homogeneous transformation that maps A on to B distances: Euclidean distances (errors) of the nearest neighbor i: number of iterations to converge |
12,554 | from scipy.spatial import Delaunay
from itertools import combinations
import numpy as np
from im2mesh.utils import voxels
def upsample3d_nn(x):
xshape = x.shape
yshape = (2*xshape[0], 2*xshape[1], 2*xshape[2])
y = np.zeros(yshape, dtype=x.dtype)
y[::2, ::2, ::2] = x
y[::2, ::2, 1::2] = x
y[::2, 1::2, ::2] = x
y[::2, 1::2, 1::2] = x
y[1::2, ::2, ::2] = x
y[1::2, ::2, 1::2] = x
y[1::2, 1::2, ::2] = x
y[1::2, 1::2, 1::2] = x
return y | null |
12,555 | from scipy.spatial import Delaunay
from itertools import combinations
import numpy as np
from im2mesh.utils import voxels
def get_tetrahedon_volume(points):
vectors = points[..., :3, :] - points[..., 3:, :]
volume = 1/6 * np.linalg.det(vectors)
return volume
def sample_tetraheda(tetraheda_points, size):
N_tetraheda = tetraheda_points.shape[0]
volume = np.abs(get_tetrahedon_volume(tetraheda_points))
probs = volume / volume.sum()
tetraheda_rnd = np.random.choice(range(N_tetraheda), p=probs, size=size)
tetraheda_rnd_points = tetraheda_points[tetraheda_rnd]
weights_rnd = np.random.dirichlet([1, 1, 1, 1], size=size)
weights_rnd = weights_rnd.reshape(size, 4, 1)
points_rnd = (weights_rnd * tetraheda_rnd_points).sum(axis=1)
# points_rnd = tetraheda_rnd_points.mean(1)
return points_rnd | null |
12,556 | import numpy as np
from .triangle_hash import TriangleHash as _TriangleHash
class MeshIntersector:
def __init__(self, mesh, resolution=512):
triangles = mesh.vertices[mesh.faces].astype(np.float64)
n_tri = triangles.shape[0]
self.resolution = resolution
self.bbox_min = triangles.reshape(3 * n_tri, 3).min(axis=0)
self.bbox_max = triangles.reshape(3 * n_tri, 3).max(axis=0)
# Tranlate and scale it to [0.5, self.resolution - 0.5]^3
self.scale = (resolution - 1) / (self.bbox_max - self.bbox_min)
self.translate = 0.5 - self.scale * self.bbox_min
self._triangles = triangles = self.rescale(triangles)
# assert(np.allclose(triangles.reshape(-1, 3).min(0), 0.5))
# assert(np.allclose(triangles.reshape(-1, 3).max(0), resolution - 0.5))
triangles2d = triangles[:, :, :2]
self._tri_intersector2d = TriangleIntersector2d(
triangles2d, resolution)
def query(self, points):
# Rescale points
points = self.rescale(points)
# placeholder result with no hits we'll fill in later
contains = np.zeros(len(points), dtype=np.bool)
# cull points outside of the axis aligned bounding box
# this avoids running ray tests unless points are close
inside_aabb = np.all(
(0 <= points) & (points <= self.resolution), axis=1)
if not inside_aabb.any():
return contains
# Only consider points inside bounding box
mask = inside_aabb
points = points[mask]
# Compute intersection depth and check order
points_indices, tri_indices = self._tri_intersector2d.query(points[:, :2])
triangles_intersect = self._triangles[tri_indices]
points_intersect = points[points_indices]
depth_intersect, abs_n_2 = self.compute_intersection_depth(
points_intersect, triangles_intersect)
# Count number of intersections in both directions
smaller_depth = depth_intersect >= points_intersect[:, 2] * abs_n_2
bigger_depth = depth_intersect < points_intersect[:, 2] * abs_n_2
points_indices_0 = points_indices[smaller_depth]
points_indices_1 = points_indices[bigger_depth]
nintersect0 = np.bincount(points_indices_0, minlength=points.shape[0])
nintersect1 = np.bincount(points_indices_1, minlength=points.shape[0])
# Check if point contained in mesh
contains1 = (np.mod(nintersect0, 2) == 1)
contains2 = (np.mod(nintersect1, 2) == 1)
if (contains1 != contains2).any():
print('Warning: contains1 != contains2 for some points.')
contains[mask] = (contains1 & contains2)
return contains
def compute_intersection_depth(self, points, triangles):
t1 = triangles[:, 0, :]
t2 = triangles[:, 1, :]
t3 = triangles[:, 2, :]
v1 = t3 - t1
v2 = t2 - t1
# v1 = v1 / np.linalg.norm(v1, axis=-1, keepdims=True)
# v2 = v2 / np.linalg.norm(v2, axis=-1, keepdims=True)
normals = np.cross(v1, v2)
alpha = np.sum(normals[:, :2] * (t1[:, :2] - points[:, :2]), axis=1)
n_2 = normals[:, 2]
t1_2 = t1[:, 2]
s_n_2 = np.sign(n_2)
abs_n_2 = np.abs(n_2)
mask = (abs_n_2 != 0)
depth_intersect = np.full(points.shape[0], np.nan)
depth_intersect[mask] = \
t1_2[mask] * abs_n_2[mask] + alpha[mask] * s_n_2[mask]
# Test the depth:
# TODO: remove and put into tests
# points_new = np.concatenate([points[:, :2], depth_intersect[:, None]], axis=1)
# alpha = (normals * t1).sum(-1)
# mask = (depth_intersect == depth_intersect)
# assert(np.allclose((points_new[mask] * normals[mask]).sum(-1),
# alpha[mask]))
return depth_intersect, abs_n_2
def rescale(self, array):
array = self.scale * array + self.translate
return array
def check_mesh_contains(mesh, points, hash_resolution=512):
intersector = MeshIntersector(mesh, hash_resolution)
contains = intersector.query(points)
return contains | null |
12,557 | import os
from plyfile import PlyElement, PlyData
import numpy as np
def load_pointcloud(in_file):
plydata = PlyData.read(in_file)
vertices = np.stack([
plydata['vertex']['x'],
plydata['vertex']['y'],
plydata['vertex']['z']
], axis=1)
return vertices | null |
12,558 | import os
from plyfile import PlyElement, PlyData
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `read_off` function. Write a Python function `def read_off(file)` to solve the following problem:
Reads vertices and faces from an off file. :param file: path to file to read :type file: str :return: vertices and faces as lists of tuples :rtype: [(float)], [(int)]
Here is the function:
def read_off(file):
"""
Reads vertices and faces from an off file.
:param file: path to file to read
:type file: str
:return: vertices and faces as lists of tuples
:rtype: [(float)], [(int)]
"""
assert os.path.exists(file), 'file %s not found' % file
with open(file, 'r') as fp:
lines = fp.readlines()
lines = [line.strip() for line in lines]
# Fix for ModelNet bug were 'OFF' and the number of vertices and faces
# are all in the first line.
if len(lines[0]) > 3:
assert lines[0][:3] == 'OFF' or lines[0][:3] == 'off', \
'invalid OFF file %s' % file
parts = lines[0][3:].split(' ')
assert len(parts) == 3
num_vertices = int(parts[0])
assert num_vertices > 0
num_faces = int(parts[1])
assert num_faces > 0
start_index = 1
# This is the regular case!
else:
assert lines[0] == 'OFF' or lines[0] == 'off', \
'invalid OFF file %s' % file
parts = lines[1].split(' ')
assert len(parts) == 3
num_vertices = int(parts[0])
assert num_vertices > 0
num_faces = int(parts[1])
assert num_faces > 0
start_index = 2
vertices = []
for i in range(num_vertices):
vertex = lines[start_index + i].split(' ')
vertex = [float(point.strip()) for point in vertex if point != '']
assert len(vertex) == 3
vertices.append(vertex)
faces = []
for i in range(num_faces):
face = lines[start_index + num_vertices + i].split(' ')
face = [index.strip() for index in face if index != '']
# check to be sure
for index in face:
assert index != '', \
'found empty vertex index: %s (%s)' \
% (lines[start_index + num_vertices + i], file)
face = [int(index) for index in face]
assert face[0] == len(face) - 1, \
'face should have %d vertices but as %d (%s)' \
% (face[0], len(face) - 1, file)
assert face[0] == 3, \
'only triangular meshes supported (%s)' % file
for index in face:
assert index >= 0 and index < num_vertices, \
'vertex %d (of %d vertices) does not exist (%s)' \
% (index, num_vertices, file)
assert len(face) > 1
faces.append(face)
return vertices, faces
assert False, 'could not open %s' % file | Reads vertices and faces from an off file. :param file: path to file to read :type file: str :return: vertices and faces as lists of tuples :rtype: [(float)], [(int)] |
12,562 | import argparse
import numpy as np
F_MM = 35.
SENSOR_SIZE_MM = 32.
PIXEL_ASPECT_RATIO = 1.
RESOLUTION_PCT = 100
SKEW = 0.
CAM_MAX_DIST = 1.75
IMG_W = 127 + 10
IMG_H = 127 + 10
CAM_ROT = np.matrix(((1.910685676922942e-15, 4.371138828673793e-08, 1.0),
(1.0, -4.371138828673793e-08, -0.0),
(4.371138828673793e-08, 1.0, -4.371138828673793e-08)))
The provided code snippet includes necessary dependencies for implementing the `getBlenderProj` function. Write a Python function `def getBlenderProj(az, el, distance_ratio, img_w=IMG_W, img_h=IMG_H)` to solve the following problem:
Calculate 4x3 3D to 2D projection matrix given viewpoint parameters.
Here is the function:
def getBlenderProj(az, el, distance_ratio, img_w=IMG_W, img_h=IMG_H):
"""Calculate 4x3 3D to 2D projection matrix given viewpoint parameters."""
# Calculate intrinsic matrix.
scale = RESOLUTION_PCT / 100
f_u = F_MM * img_w * scale / SENSOR_SIZE_MM
f_v = F_MM * img_h * scale * PIXEL_ASPECT_RATIO / SENSOR_SIZE_MM
u_0 = img_w * scale / 2
v_0 = img_h * scale / 2
K = np.matrix(((f_u, SKEW, u_0), (0, f_v, v_0), (0, 0, 1)))
# Calculate rotation and translation matrices.
# Step 1: World coordinate to object coordinate.
sa = np.sin(np.radians(-az))
ca = np.cos(np.radians(-az))
se = np.sin(np.radians(-el))
ce = np.cos(np.radians(-el))
R_world2obj = np.transpose(np.matrix(((ca * ce, -sa, ca * se),
(sa * ce, ca, sa * se),
(-se, 0, ce))))
# Step 2: Object coordinate to camera coordinate.
R_obj2cam = np.transpose(np.matrix(CAM_ROT))
R_world2cam = R_obj2cam * R_world2obj
cam_location = np.transpose(np.matrix((distance_ratio * CAM_MAX_DIST,
0,
0)))
T_world2cam = -1 * R_obj2cam * cam_location
# Step 3: Fix blender camera's y and z axis direction.
R_camfix = np.matrix(((1, 0, 0), (0, -1, 0), (0, 0, -1)))
R_world2cam = R_camfix * R_world2cam
T_world2cam = R_camfix * T_world2cam
RT = np.hstack((R_world2cam, T_world2cam))
return K, RT | Calculate 4x3 3D to 2D projection matrix given viewpoint parameters. |
12,563 | import argparse
import trimesh
import numpy as np
import os
import glob
import sys
from multiprocessing import Pool
from functools import partial
from im2mesh.utils import binvox_rw, voxels
from im2mesh.utils.libmesh import check_mesh_contains
def export_pointcloud(mesh, modelname, loc, scale, args):
filename = os.path.join(args.pointcloud_folder,
modelname + '.npz')
if not args.overwrite and os.path.exists(filename):
print('Pointcloud already exist: %s' % filename)
return
points, face_idx = mesh.sample(args.pointcloud_size, return_index=True)
normals = mesh.face_normals[face_idx]
# Compress
if args.float16:
dtype = np.float16
else:
dtype = np.float32
points = points.astype(dtype)
normals = normals.astype(dtype)
print('Writing pointcloud: %s' % filename)
np.savez(filename, points=points, normals=normals, loc=loc, scale=scale)
def export_voxels(mesh, modelname, loc, scale, args):
if not mesh.is_watertight:
print('Warning: mesh %s is not watertight!'
'Cannot create voxelization.' % modelname)
return
filename = os.path.join(args.voxels_folder, modelname + '.binvox')
if not args.overwrite and os.path.exists(filename):
print('Voxels already exist: %s' % filename)
return
res = args.voxels_res
voxels_occ = voxels.voxelize(mesh, res)
voxels_out = binvox_rw.Voxels(voxels_occ, (res,) * 3,
translate=loc, scale=scale,
axis_order='xyz')
print('Writing voxels: %s' % filename)
with open(filename, 'bw') as f:
voxels_out.write(f)
def export_points(mesh, modelname, loc, scale, args):
if not mesh.is_watertight:
print('Warning: mesh %s is not watertight!'
'Cannot sample points.' % modelname)
return
filename = os.path.join(args.points_folder, modelname + '.npz')
if not args.overwrite and os.path.exists(filename):
print('Points already exist: %s' % filename)
return
n_points_uniform = int(args.points_size * args.points_uniform_ratio)
n_points_surface = args.points_size - n_points_uniform
boxsize = 1 + args.points_padding
points_uniform = np.random.rand(n_points_uniform, 3)
points_uniform = boxsize * (points_uniform - 0.5)
points_surface = mesh.sample(n_points_surface)
points_surface += args.points_sigma * np.random.randn(n_points_surface, 3)
points = np.concatenate([points_uniform, points_surface], axis=0)
occupancies = check_mesh_contains(mesh, points)
# Compress
if args.float16:
dtype = np.float16
else:
dtype = np.float32
points = points.astype(dtype)
if args.packbits:
occupancies = np.packbits(occupancies)
print('Writing points: %s' % filename)
np.savez(filename, points=points, occupancies=occupancies,
loc=loc, scale=scale)
def export_mesh(mesh, modelname, loc, scale, args):
filename = os.path.join(args.mesh_folder, modelname + '.off')
if not args.overwrite and os.path.exists(filename):
print('Mesh already exist: %s' % filename)
return
print('Writing mesh: %s' % filename)
mesh.export(filename)
def process_path(in_path, args):
in_file = os.path.basename(in_path)
modelname = os.path.splitext(in_file)[0]
mesh = trimesh.load(in_path, process=False)
# Determine bounding box
if not args.resize:
# Standard bounding boux
loc = np.zeros(3)
scale = 1.
else:
if args.bbox_in_folder is not None:
in_path_tmp = os.path.join(args.bbox_in_folder, modelname + '.off')
mesh_tmp = trimesh.load(in_path_tmp, process=False)
bbox = mesh_tmp.bounding_box.bounds
else:
bbox = mesh.bounding_box.bounds
# Compute location and scale
loc = (bbox[0] + bbox[1]) / 2
scale = (bbox[1] - bbox[0]).max() / (1 - args.bbox_padding)
# Transform input mesh
mesh.apply_translation(-loc)
mesh.apply_scale(1 / scale)
if args.rotate_xz != 0:
angle = args.rotate_xz / 180 * np.pi
R = trimesh.transformations.rotation_matrix(angle, [0, 1, 0])
mesh.apply_transform(R)
# Expert various modalities
if args.pointcloud_folder is not None:
export_pointcloud(mesh, modelname, loc, scale, args)
if args.voxels_folder is not None:
export_voxels(mesh, modelname, loc, scale, args)
if args.points_folder is not None:
export_points(mesh, modelname, loc, scale, args)
if args.mesh_folder is not None:
export_mesh(mesh, modelname, loc, scale, args) | null |
12,564 | import sys
import datetime
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMessageBox, qApp
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import (
QtInfoMsg,
QtWarningMsg,
QtCriticalMsg,
QtFatalMsg
)
def qt_message_handler(mode, context, message):
if mode == QtInfoMsg:
mode = 'INFO'
elif mode == QtWarningMsg:
mode = 'WARNING'
elif mode == QtCriticalMsg:
mode = 'CRITICAL'
elif mode == QtFatalMsg:
mode = 'FATAL'
else:
mode = 'DEBUG'
msg = message.split("@$ff$@")
if len(msg) == 2 and msg[0] == "True":
with open("/etc/v2rayL/v2rayL_op.log", "a+") as f:
f.write(' %s - %s: %s\n' % (datetime.datetime.now(), mode, msg[1])) | null |
12,565 | from collections import defaultdict
import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,566 | import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,568 | import sys
import re
def input():
return sys.stdin.readline().rstrip() | null |
12,572 | import sys
def palin(start, end, del_cnt):
if del_cnt == 2:
return del_cnt
while start <= end:
if string[start] != string[end]:
a = palin(start + 1, end, del_cnt + 1)
b = palin(start, end - 1, del_cnt + 1)
return a if a <= b else b
start += 1
end -= 1
else:
return del_cnt | null |
12,582 | import sys
start = list(map(int, input().split(':')))
end = list(map(int, input().split(':')))
def isBig():
if start[0] < end[0]:
return 1
elif start[0] == end[0]:
if start[1] < end[1]:
return 1
elif start[1] == end[1]:
if start[2] < end[2]:
return 1
elif start[2] == end[2]:
return 0
else:
return -1
else:
return -1
else:
return -1 | null |
12,584 | import sys
def GCD(x,y):
if y == 0:
return x
else:
return GCD(y, x%y) | null |
12,590 | import sys
return max(range(len(a)), key=lambda x: a[x]
def argmax(a):
return max(range(len(a)), key=lambda x: a[x]) | null |
12,593 | from collections import deque
import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,594 | from collections import deque
import sys
board = [[0]*N for _ in range(N)]
visit = [[[False]*N for _ in range(N)] for _ in range(2)]
def bfs(molds, t):
def solution(cleans, molds):
global board, visit
molds = deque(molds)
for _t in range(t):
molds = bfs(molds, _t)
for clean in cleans:
y, x = clean
if visit[(_t+1)%2][y][x]==1:
return True
return False | null |
12,596 | import sys
def change(num, first = False):
ret = ''
while num:
ret += chr(num % 2 + 48)
num //= 2
while len(ret) < 3:
ret += '0'
idx = 3
if first:
while idx > 1 and ret[idx - 1] == '0':
idx -= 1
return ret[:idx][::-1] | null |
12,598 | import sys
r_num = len(arr)
c_num = len(arr[0])
temp = [arr[-(row + 1)] for row in range(r_num)]
return tem
temp = [arr[row][::-1] for row in range(arr_N)]
return tem
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return temp
r_num = len(arr)
c_num = len(arr[0])
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp
r_num = len(arr)
c_num = len(arr[0])
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return tem
for row in array:
print(' '.join(row))
def fun1(arr):
r_num = len(arr)
c_num = len(arr[0])
temp = [arr[-(row + 1)] for row in range(r_num)]
return temp | null |
12,599 | import sys
temp = [arr[-(row + 1)] for row in range(r_num)]
return tem
arr_M = len(arr[0])
temp = [arr[row][::-1] for row in range(arr_N)]
return tem
arr_M = len(arr[0])
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp
arr_N = len(arr)
arr_M = len(arr[0])
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return tem len(arr)
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return tem
for row in array:
print(' '.join(row))
def fun2(arr):
arr_N = len(arr)
arr_M = len(arr[0])
temp = [arr[row][::-1] for row in range(arr_N)]
return temp | null |
12,600 | import sys
temp = [arr[-(row + 1)] for row in range(r_num)]
return tem
arr_M = len(arr[0])
temp = [arr[row][::-1] for row in range(arr_N)]
return tem
arr_M = len(arr[0])
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp
arr_N = len(arr)
arr_M = len(arr[0])
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return tem len(arr)
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return tem
for row in array:
print(' '.join(row))
def fun3(arr):
arr_N = len(arr)
arr_M = len(arr[0])
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp | null |
12,601 | import sys
temp = [arr[-(row + 1)] for row in range(r_num)]
return tem
arr_M = len(arr[0])
temp = [arr[row][::-1] for row in range(arr_N)]
return tem
arr_M = len(arr[0])
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp
arr_N = len(arr)
arr_M = len(arr[0])
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return tem len(arr)
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return tem
for row in array:
print(' '.join(row))
def fun4(arr):
arr_N = len(arr)
arr_M = len(arr[0])
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return temp | null |
12,602 | import sys
r_num = len(arr)
c_num = len(arr[0])
temp = [arr[-(row + 1)] for row in range(r_num)]
return tem
temp = [arr[row][::-1] for row in range(arr_N)]
return tem
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return temp
r_num = len(arr)
c_num = len(arr[0])
h_rn = r_num // 2
h_cn = c_num // 2
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp
r_num = len(arr)
c_num = len(arr[0])
h_rn = r_num // 2
h_cn = c_num // 2
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return tem
for row in array:
print(' '.join(row))
def fun5(arr):
r_num = len(arr)
c_num = len(arr[0])
h_rn = r_num // 2
h_cn = c_num // 2
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp | null |
12,603 | import sys
r_num = len(arr)
c_num = len(arr[0])
temp = [arr[-(row + 1)] for row in range(r_num)]
return tem
temp = [arr[row][::-1] for row in range(arr_N)]
return tem
temp = [[arr[-(col + 1)][row] for col in range(arr_N)] for row in range(arr_M)]
return temp
temp = [[arr[col][-(row + 1)] for col in range(arr_N)] for row in range(arr_M)]
return temp
r_num = len(arr)
c_num = len(arr[0])
h_rn = r_num // 2
h_cn = c_num // 2
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row - h_rn][col]
return temp
r_num = len(arr)
c_num = len(arr[0])
h_rn = r_num // 2
h_cn = c_num // 2
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return tem
for row in array:
print(' '.join(row))
def fun6(arr):
r_num = len(arr)
c_num = len(arr[0])
h_rn = r_num // 2
h_cn = c_num // 2
temp = [[0] * c_num for _ in range(r_num)]
for row in range(r_num):
for col in range(c_num):
if row < h_rn and col < h_cn:
temp[row][col] = arr[row][col + h_cn]
elif row < h_rn and col >= h_cn:
temp[row][col] = arr[row + h_rn][col]
elif row >= h_rn and col < h_cn:
temp[row][col] = arr[row - h_rn][col]
elif row >= h_rn and col >= h_cn:
temp[row][col] = arr[row][col - h_cn]
return temp | null |
12,605 | import sys
from collections import deque
def input():
return sys.stdin.readline().rstrip() | null |
12,607 | import sys
N, M = map(int, input().split())
arr = []
nx = [-1, 0, 1, 0]
ny = [0, -1, 0, 1]
dp = [[-1 for i in range(M)] for j in range(N)]
for i in range(N):
arr.append(list(map(int, input().split())))
def DFS(x,y):
if x == N-1 and y == M-1:
return 1
if dp[x][y] == -1:
dp[x][y] = 0
for i in range(4):
dx = nx[i] + x
dy = ny[i] + y
if dx < 0 or dx >= N or dy < 0 or dy >= M:
continue
if arr[dx][dy] < arr[x][y]:
dp[x][y] += DFS(dx,dy)
return dp[x][y] | null |
12,612 | import sys
import heapq
def input():
return sys.stdin.readline().rstrip() | null |
12,615 | import sys
tree = [[] for _ in range(n)]
for nei in tree[v]:
# Leaf까지 내려감
dp(nei)
# 각 child를 root로 하는 subtree에 정보 전달하는데 걸리는 시간 모음
child_t.append(time[nei])
if not tree[v]:
# Child가 없으면 0
child_t.append(0)
child_t.sort(reverse=True)
or i in range(len(child_t))]
time[v] = max(need_time)
def dp(v):
child_t = []
for nei in tree[v]:
# Leaf까지 내려감
dp(nei)
# 각 child를 root로 하는 subtree에 정보 전달하는데 걸리는 시간 모음
child_t.append(time[nei])
if not tree[v]:
# Child가 없으면 0
child_t.append(0)
child_t.sort(reverse=True)
# 시간이 오래 걸리는 쪽부터 먼저 전화를 돌리기
need_time = [child_t[i] + i + 1 for i in range(len(child_t))]
time[v] = max(need_time) # 그 중에 가장 오래 걸리는 시간을 assign | null |
12,616 | import sys
sys.setrecursionlimit(1000000000)
def input():
return sys.stdin.readline().rstrip() | null |
12,617 | import sys
tree = [[] for _ in range(n+1)]
stat = list(map(int, input().split()))
def dp(v):
con = 0
for nei in tree[v]:
dp(nei)
# Node v를 사용하지 않는 경우 -> max(dp_mat[nei]) 선택
# nei가 멘토든 아니든 상관 없이 가장 큰 경우만 가져오면 됨
dp_mat[v][1] += max(dp_mat[nei][0], dp_mat[nei][1])
# Node v를 사용하는 경우 -> 취사선택이 필요함!
# 이 경우 nei 중 하나 x를 선택해서 v의 멘티로 삼게 됨
# x를 제외한 나머지 nei는 max(dp_mat[nei]) 취사선택
# x를 멘티로 삼는 경우, x가 멘토인 경우와 아닌 경우를 고려해야 함
# dp_mat[v][1] 연산 시 dp_mat[x][1](x 미포함)을 사용하면 문제 없음
# 만약 dp_mat[nei][0]을 사용했다면 x의 멘토 관계를 해제하고 v의 멘티로 삼아야 함
# 이 경우 무조건 dp_mat[x][0] 대신 dp_mat[x][1]을 사용해야 함
# dp_mat[v][1]에 영향이 가게 됨 -> 이 영향을 con으로 계산, con을 가장 크게 만드는 x 선택
con = max(con, stat[v-1]*stat[nei-1] - max(dp_mat[nei][0]-dp_mat[nei][1], 0))
dp_mat[v][0] = dp_mat[v][1]+con | null |
12,618 | import sys
sys.setrecursionlimit(1000000)(int, input().split())
def input():
return sys.stdin.readline().rstrip() | null |
12,619 | import sys
tree = [[] for _ in range(n+1)]
num_child = [0]*(n+1)
def dfs(cur, parent):
if len(tree[cur]) == 1 and parent != -1: # Leaf node라면
num_child[cur] = 1
return 1
n_sub = 0 # cur를 root로 하는 subtree의 node 개수
for child in tree[cur]:
if child != parent: # 각 child를 root로 하는 subtree의 node 개수 추가
n_sub += dfs(child, cur)
num_child[cur] = n_sub + 1 # 본인 추가
return n_sub + 1 | null |
12,620 | import sys
from itertools import permutations
def input():
return sys.stdin.readline().rstrip() | null |
12,621 | import sys
from itertools import combinations
def input():
return sys.stdin.readline().rstrip() | null |
12,622 | import sys
from itertools import combinations
N = int(input())
pop = list(map(int, input().split()))
pop.insert(0,0)
arr = [[] for i in range(N+1)]
for i in range(1, N+1):
t = list(map(int, input().split()))
arr[i] = t[1:]
for i in range(1, N):
comb_list = list(combinations(stan, i))
for comb in comb_list:
visited = [0] * (N+1)
remain = [j for j in range(1,N+1) if j not in comb]
ct = 0
first = DFS(comb[0], comb)
ct = 0
second = DFS(remain[0], remain)
if visited.count(1) == N:
MIN = min(MIN, abs(first - second))
def DFS(x, ar):
global ct
ct += pop[x]
visited[x] = 1
for i in range(1, N+1):
if i in arr[x] and visited[i] == 0 and i in ar:
visited[i] = 1
DFS(i, ar)
return ct | null |
12,626 | import sys
from math import sqrt
def input():
return sys.stdin.readline().rstrip() | null |
12,627 | import sys
from math import sqrt
sqrtN = int(sqrt(N))
def solve(N):
ret = 4
for a in range(1, sqrtN + 1):
if a * a == N:
ret = 1
if ret == 1:
break
for b in range(1, sqrtN + 1):
if a * a + b * b > N:
break
if a * a + b * b == N:
ret = 2
if ret <= 2:
break
for c in range(1, sqrtN + 1):
if a * a + b * b + c * c > N:
break
if a * a + b * b + c * c == N:
ret = 3
break
return ret | null |
12,630 | from collections import deque
import sys
for i in range(a):
li = list(map(int, input().split()))
for j in range(b):
if li[j] == 1:
sticker[c][1].append((i, j))
def rotate(arr, N):
result = []
i_array = []
j_array = []
for item in arr:
i,j = item
i_array.append(j)
j_array.append(N-i-1)
result.append((j,N-i-1))
i_min = min(i_array)
j_min = min(j_array)
real_result = []
for item in result:
y,x = item
real_result.append((y-i_min,x-j_min))
return real_result | null |
12,631 | from collections import deque
import sys
for i in range(a):
li = list(map(int, input().split()))
for j in range(b):
if li[j] == 1:
sticker[c][1].append((i, j))
def check(n,m,arr,visit):
for i in range(n):
for j in range(m):
chk = True
temp = set()
for y,x in arr:
if y+i<n and x+j<m:
if (y+i,x+j) in visit:
chk = False
break
else:
temp.add((y+i,x+j))
else:
chk = False
break
if chk:
return (True, temp)
return (False, None) | null |
12,634 | from itertools import combinations
from collections import deque
import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,635 | from itertools import combinations
from collections import deque
import sys
def bfs(start1, start2, graph, N):
result = [99999999 for _ in range(N+1)]
result[0] = 0 # 인덱스 0은 더미
result[start1] = 0
result[start2] = 0
q = deque()
q.append((start1, 0))
q.append((start2, 0))
visit = set()
visit.add(start1)
visit.add(start2)
while q:
if len(visit) == N:
break
cur, dist = q.popleft()
for nxt in graph[cur]:
if nxt in visit: continue
visit.add(nxt)
q.append((nxt, dist + 1))
result[nxt] = dist + 1
return sum(result)
def solution(graph, N):
candidate = [i for i in range(1, N+1)]
answer = 99999999
fin_store1 = N+1
fin_store2 = N+1
for comb in combinations(candidate, 2):
store1, store2 = comb
result = bfs(store1, store2, graph, N)
if answer > result:
fin_store1 = store1
fin_store2 = store2
answer = result
elif answer == result:
if fin_store1 > store1:
fin_store1 = store1
fin_store2 = store2
answer = result
elif fin_store1 == store1:
if fin_store2 > store2:
fin_store1 = store1
fin_store2 = store2
answer = result
return ' '.join(map(str, [fin_store1, fin_store2, answer * 2])) | null |
12,636 | from itertools import permutations
import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,637 | from itertools import permutations
import sys
def shuffle(card1, card2, card3):
card = card2 + card1 + card3
if len(card2) > 1:
return shuffle(card2[:len(card2)//2] + card1, card2[len(card2)//2:], card3)
else:
card = card2 + card1 + card3
return card | null |
12,641 | import sys
def isDifferentAndNotZero(num):
if num[0] == num[1] or num[0] == num[2] or num[1] == num[2]:
return False
if '0' in num:
return False
return True | null |
12,642 | import sys
N = int(input())
arr = []
for i in range(N):
num, strike, ball = input().split()
arr.append([num, int(strike), int(ball)])
for i in range(123,988):
if isDifferentAndNotZero(str(i)) and baseball(str(i)):
ans += 1
def baseball(num):
flag = 0
for i in range(N):
strike, ball = 0,0
for j in range(3):
if num[j] == arr[i][0][j]:
strike += 1
if num[0] == arr[i][0][1] or num[0] == arr[i][0][2]:
ball += 1
if num[1] == arr[i][0][0] or num[1] == arr[i][0][2]:
ball += 1
if num[2] == arr[i][0][0] or num[2] == arr[i][0][1]:
ball += 1
if strike == arr[i][1] and ball == arr[i][2]:
flag += 1
if flag == N:
return True
else:
return False | null |
12,643 | import sys
from itertools import combinations as combi
def input():
return sys.stdin.readline().rstrip() | null |
12,644 | import sys
from itertools import combinations as combi
N, M = map(int,input().split())st(map(int,input().split()))
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if check[nx][ny]:
#4개블럭값이 이전 블럭값이면 안되니까 false 해주고
check[nx][ny] = False
dfs(nx,ny,val+board[nx][ny],depth+1)
#끝난후 다시 방문가능처리해줌.
check[nx][ny] = True
for i in range(N):
for j in range(M):
#시작블록을 다시방문하면안됨
check[i][j] = False
dfs(i,j,board[i][j],1)
#끝난후 다시 방문가능처리
check[i][j] = True
temp = block_T(i,j)
answer = max(answer,temp)
def block_T(x,y):
#중앙의 한 점이라고 가정한다
result = board[x][y]
# 상하좌우의 티어나온부분 중 날개가 4개면
# 제일작은 값을 제거한값이 최대값이 될것이고,
# 날개가 2개라면 T가아니고 날개가 3개라면 그냥 그값을 리턴해준다.
wings = 4
MIN = int(1e9)
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if wings == 2:
return 0
#꼬다리부분이 맵을 벗어난다? 그방향 날개는 없는것.
if not (0<=nx<N and 0<=ny<M):
wings -= 1
continue
#모든 날개 값들을 더해준다.
result+= board[nx][ny]
if MIN > board[nx][ny]:
MIN = board[nx][ny]
#모든방향 날개가 살아있단 말이므로 4방향의 날개중 제일 작은날개 하나를 잘라준다.
if wings == 4:
result -= MIN
return result | null |
12,645 | import sys
from itertools import combinations as combi
N, M = map(int,input().split())st(map(int,input().split()))
global answer
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if check[nx][ny]:
#4개블럭값이 이전 블럭값이면 안되니까 false 해주고
check[nx][ny] = False
dfs(nx,ny,val+board[nx][ny],depth+1)
#끝난후 다시 방문가능처리해줌.
check[nx][ny] = True
for i in range(N):
for j in range(M):
#시작블록을 다시방문하면안됨
check[i][j] = False
dfs(i,j,board[i][j],1)
#끝난후 다시 방문가능처리
check[i][j] = True
temp = block_T(i,j)
answer = max(answer,temp)
def dfs(x,y,val,depth):
global answer
if depth == 4:
answer = max(answer,val)
return
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if check[nx][ny]:
#4개블럭값이 이전 블럭값이면 안되니까 false 해주고
check[nx][ny] = False
dfs(nx,ny,val+board[nx][ny],depth+1)
#끝난후 다시 방문가능처리해줌.
check[nx][ny] = True | null |
12,647 | import sys
N, C = map(int, input().split())
K = list(map(int, input().split()))
ans = 0
def backTracking(num):
global ans
if num > N:
return
ans = max(ans,num)
for i in K:
num = num * 10 + i
backTracking(num)
num = (num - i) // 10 | null |
12,649 | import sys
def isPalindrome(s):
return s == s[::-1] | null |
12,652 | import sys
arr = []
for i in range(9):
arr.append(int(input()))
arr.remove(first)
arr.remove(second)
arr.sort()
for i in arr:
print(i)
def findIndex(ans):
for i in range(9):
for j in range(i+1,9):
if arr[i] + arr[j] == ans:
return (arr[i], arr[j]) | null |
12,655 | from bisect import bisect_left
import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,657 | import sys
arr = []
K = 0
for i in range(N):
arr.append(int(input()))
def binary_search():
global K
start, end = max(arr), sum(arr)
while start <= end:
mid = (start + end) // 2
have,ct = 0,0
for i in arr:
if have < i:
have = mid - i
ct += 1
else:
have = have - i
if ct > M:
start = mid + 1
else:
end = mid - 1
K = mid | null |
12,659 | import sys
arr = list(map(int, input().split()))
M = int(input())
def binary_search():
start, end = 0, max(arr)
while start <= end:
mid = (start + end) // 2
total = 0
for i in arr:
if mid < i:
total += mid
else:
total += i
if total <= M:
start = mid + 1
else:
end = mid - 1
return end | null |
12,660 | import sys
from bisect import bisect_left, bisect_right
def input():
return sys.stdin.readline().rstrip() | null |
12,662 | import sys
def binary_search(t):
start, end = 0, len(arr)-1
while start <= end:
mid = (start + end) // 2
if arr[mid] == t:
return 1
elif arr[mid] > t:
end = mid - 1
else:
start = mid + 1
return 0 | null |
12,664 | import sys
arr = []
ans = 0
for i in range(K):
arr.append(int(input()))
def binary_search():
global ans
start, end = 1, max(arr)
while start <= end:
ct = 0
mid = (start + end) // 2
for i in arr:
ct += i // mid
if ct < N:
end = mid - 1
else:
start = mid + 1
ans = end | null |
12,666 | import sys
arr = list(map(int, input().split()))
ans = 0
def binary_search():
global ans
start, end = 0, max(arr)
while start <= end:
mid = (start + end) // 2
total_length = 0
for i in arr:
if i - mid >= 0:
total_length += i - mid
if total_length < M:
end = mid - 1
else:
start = mid + 1
ans = end | null |
12,681 | import heapq
import sys
def input():
return sys.stdin.readline().rstrip() | null |
12,685 | import sys
n, f_kind, max_seq, coupon = map(int, input().split())
eat = [0 for _ in range(3000001)]
def answer(line, max_seq, coupon):
count = 0
for i in range(max_seq):
food_number = line[i]
if not eat[food_number]:
count += 1
eat[food_number] += 1
max_count = count
for i in range(1, n):
if max_count <= count:
if not eat[coupon]:
max_count = count + 1
else:
max_count = count
out = i - 1
eat[line[out]] -= 1
if not eat[line[out]]:
count -= 1
in_ = (i + max_seq - 1) % n
if not eat[line[in_]]:
count += 1
eat[line[in_]] += 1
return max_count | null |
12,691 | import sys
def origami(start, end):
if start == end:
return True
mid = (start + end) // 2
sign = True
for i in range(start,mid):
if status[i] == status[end-i]:
sign = False
break
if sign:
return origami(start, mid - 1) and origami(mid + 1, end)
else:
return False | null |
12,693 | import sys
def find_parent(x):
if parent[x] != x:
parent[x] = find_parent(parent[x])
return parent[x]
parent = [i for i in range(N)]
def union(x,y):
x = find_parent(x)
y = find_parent(y)
if x < y:
parent[y] = x
else:
parent[x] = y | null |
12,695 | import sys
gates = list(range(G + 1))
def find_max(x):
if gates[x] != x:
gates[x] = find_max(gates[x])
return gates[x] | null |
12,697 | import sys
dis_set = [-1]*(n+1)
if dis_set[x] < 0: # 해당 disjoint set의 최상단 root를 찾음
return x
def find(x):
def union(x, y):
x_root = find(x)
y_root = find(y)
if x_root != y_root: #두 node의 root가 다르다면 -> 합쳐야 함
dis_set[y_root] = x_root | null |
12,699 | import sys
from copy import deepcopy
from collections import deque
def input():
return sys.stdin.readline().rstrip() | null |
12,703 | import sys
from collections import deque
N, L, R = map(int, input().split())
arr = []
nx = [-1, 0, 1, 0]
ny = [0, -1, 0, 1]
for i in range(N):
arr.append(list(map(int, input().split())))
while True:
flag = 0
visited = [[0 for i in range(N)] for j in range(N)]
for i in range(N):
for j in range(N):
if visited[i][j] == 0:
ans = deque()
total = arr[i][j]
visited[i][j] = 1
BFS(i,j)
if len(ans) > 1:
aver = total // len(ans)
while ans:
a = ans.popleft()
arr[a[0]][a[1]] = aver
if not flag:
break
day += 1
def BFS(x,y):
global flag, total
queue = deque()
queue.append((x,y))
ans.append((x,y))
while queue:
q = queue.popleft()
for i in range(4):
dx = nx[i] + q[0]
dy = ny[i] + q[1]
if dx < 0 or dx >= N or dy < 0 or dy >= N:
continue
if visited[dx][dy] == 1:
continue
if abs(arr[dx][dy] - arr[q[0]][q[1]]) >= L and abs(arr[dx][dy] - arr[q[0]][q[1]]) <= R:
visited[dx][dy] = 1
flag = 1
total += arr[dx][dy]
queue.append((dx,dy))
ans.append((dx,dy)) | null |
12,704 | import sys
from collections import deque
from copy import deepcopy
def input():
return sys.stdin.readline().rstrip() | null |
12,708 | import sys
from math import sqrt
def GCD(x,y):
if y == 0:
return x
else:
return GCD(y, x%y) | null |
12,715 | import sys
from collections import defaultdict
def input():
return sys.stdin.readline().rstrip() | null |
12,722 | import sys
month_days = calculate_days_per_month()
day, time = L.split('/')
day = int(day)
def calculate_days_per_month():
month_days = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
days = [0]
for month, day in month_days.items():
days.append(days[month-1] + day)
return days | null |
12,723 | import sys
def change_str(_str):
date, time, item, person = _str.split()
_, month, day = map(int, date.split('-')) # 년도 필요없음
hour, minute = map(int, time.split(':'))
return person, item, (month_days[month-1] + day) * 24 * 60 + hour * 60 + minute
def solution(info, deadline_time, F):
dic = {}
people = {} # 벌금 낼 사람들
for data in info:
result = -1
person, item, time = change_str(data)
if person not in dic:
dic[person] = {}
if item in dic[person]:
result = time - dic[person].pop(item)
else:
dic[person][item] = time
if result > deadline_time:
if person not in people:
people[person] = 0
people[person] += (result - deadline_time) * F
if people:
people = sorted(people.items(), key = lambda x: x[0])
for person, pay in people:
print('{} {}'.format(person, pay))
else:
print(-1) | null |
12,724 | import sys
import heapq
from collections import defaultdict
def input():
return sys.stdin.readline().rstrip() | null |
12,727 | import sys
def find_parent(x):
if x != parent[x]:
parent[x] = find_parent(parent[x])
return parent[x]
parent = [i for i in range(N+1)]
def union(x, y):
x = find_parent(x)
y = find_parent(y)
if x < y:
parent[y] = x
else:
parent[x] = y | null |
12,728 | import sys, math
def input():
return sys.stdin.readline().rstrip() | null |
12,729 | import sys, math
def find(parent, a):
if parent[a] == a:
return a
parent[a] = find(parent, parent[a])
return parent[a]
def union(parent, a, b):
a = find(parent, a)
b = find(parent, b)
if a > b:
parent[a] = b
return True
elif a < b:
parent[b] = a
return True
return False | null |
12,731 | import sys
import heapq
parents = list(range(N + 1))
def find_parent(x):
if parents[x] != x:
parents[x] = find_parent(parents[x])
return parents[x]
def union_set(a, b):
parent_a = find_parent(a)
parent_b = find_parent(b)
if parent_a < parent_b:
parents[parent_b] = parent_a
else:
parents[parent_a] = parent_b | null |
12,733 | import sys
def find_parent(x):
parent = [i for i in range(N+1)]
def union(x,y):
x, y = find_parent(x), find_parent(y)
if x < y:
parent[y] = x
else:
parent[x] = y | null |
12,735 | import sys
import heapq
def find_parent(p):
p_parents = [i for i in range(N)]
def union_planet(p1, p2):
p1_parent = find_parent(p1)
p2_parent = find_parent(p2)
if p1_parent == p2_parent:
return False
if p1_parent < p2_parent:
p_parents[p2_parent] = p1_parent
else:
p_parents[p1_parent] = p2_parent
return True | null |
12,737 | import sys
def find_parent(x):
if x != parent[x]:
parent[x] = find_parent(parent[x])
return parent[x]
parent = [i for i in range(N+1)]
if parent.count(parent[1]) == N:
print(total - total_tree)
else:
print(-1)
def union(x, y):
x = find_parent(parent[x])
y = find_parent(parent[y])
if x < y:
parent[y] = x
else:
parent[x] = y | null |
12,739 | import sys
while True:
n, m = map(int, input().split())
if n == 0 and m == 0:
break
edge = []
total = 0
for _ in range(m):
x, y, w = map(int, input().split())
edge.append([x, y, w])
total += w
num_edge = 0
edge.sort(key=lambda x: -x[2])
# Disjoint set 구성
dis_set = [-1 for _ in range(n+1)]
def find_root(x):
change_lst = []
res = upward(x, change_lst)
for idx in change_lst:
dis_set[idx] = res
return res
# 크루스칼 시작
sol = 0
while num_edge < n-1:
x, y, w = edge.pop()
if find_root(x) != find_root(y):
union(x, y)
sol += w
num_edge += 1
print(total - sol)
def union(x, y):
x_root = find_root(x)
y_root = find_root(y)
if x_root != y_root: # 두 node의 root가 다르다면?
if dis_set[x_root] < dis_set[y_root]:
dis_set[y_root] = x_root
if dis_set[x_root] > dis_set[y_root]:
dis_set[x_root] = y_root
else:
dis_set[x_root] = -1
dis_set[y_root] = x_root | null |
12,748 | import sys
s = input()
index = [ -1 for _ in range(N) ]
current_index = 0
index[idx] = current_index
current_index += 1
index[idx] = stack.pop()
choose =
choose[cnt] = 1
choose[cnt] = 0
def func(cnt):
if cnt == current_index:
erase_bracket_count = sum(choose)
if erase_bracket_count == 0:
return
string = ""
for idx, ch in enumerate(s):
# index[idx] == -1 인 경우 (괄호가 아니므로 추가)
# 만약 -1이면 뒤에 조건문이 실행 안됨
if index[idx] == -1 or choose[index[idx]] == 0:
string += ch
answer.append(string)
return
choose[cnt] = 1 # 해당 괄호쌍을 지운 경우
func(cnt + 1)
choose[cnt] = 0 # 해당 괄호쌍을 지우지 않은 경우
func(cnt + 1) | null |
12,757 | import sys
stack = []
if stack:
print(0)
exit(0)
def compress():
# Integer를 하나로 합쳐야 하니깐 길이가 2 이상이어야 함.
while len(stack) > 1:
# 두 개의 값이 무조건 Integer이어야 하므로
# Integer면 첫번째 원소가 None으로 되어 있음
a, integer1 = stack[-1]
b, integer2 = stack[-2]
if a or b:
break
stack.pop()
stack.pop()
stack.append((None, integer1 + integer2)) | null |
12,759 | import sys
N, M = map(int, input().split())
arr = sorted(list(map(int, input().split())))
choose = [ 0 for _ in range(10) ]
def dfs(idx, cnt):
global N, M
if cnt == M:
for idx in range(cnt):
print(arr[choose[idx]], end=' ')
print()
return
for i in range(idx,N):
choose[cnt] = i
dfs(i, cnt + 1) | null |
12,761 | import sys
N, M = map(int, input().split())
choose = [ 0 for _ in range(10) ]
used = [ 0 for _ in range(10) ]
def dfs(idx, cnt):
global N, M
if cnt == M:
for idx in range(cnt):
print(choose[idx], end=' ')
print()
return
for i in range(idx, N + 1):
if used[i]:
continue
used[i] = 1
choose[cnt] = i
dfs(i + 1, cnt + 1)
used[i] = 0 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.