Skip to content

Instantly share code, notes, and snippets.

View ArthurDelannoyazerty's full-sized avatar

Arthur Delannoy ArthurDelannoyazerty

View GitHub Profile
@ArthurDelannoyazerty
ArthurDelannoyazerty / pytorch_find_cycles.py
Created March 27, 2024 11:09
A pure pytorch to find triangles (3 cycles)
class TriangleIndexes(nn.Module):
def __init__(self, adjacency_matrix):
super().__init__()
self.adjacency_matrix = adjacency_matrix
def forward(self):
# tensor of indexes of each neighbors of each nodes
nonzero = self.adjacency_matrix.nonzero()
neighbors_one_indexes = nonzero.reshape(self.adjacency_matrix.shape[0],15,2)[:,:,1].clone()
neighbors_two_indexes = neighbors_one_indexes[neighbors_one_indexes] # Tensor for each 2 neighbors for each nodes (neighbors of neighbors)
@ArthurDelannoyazerty
ArthurDelannoyazerty / dict_type_transfer.py
Created March 29, 2024 15:08
Recursively convert all set values in a nested dictionary to lists.
def sets_to_lists(nested_dict):
for key, value in nested_dict.items():
if isinstance(value, set):
nested_dict[key] = list(value)
elif isinstance(value, dict):
sets_to_lists(value)
return nested_dict
@ArthurDelannoyazerty
ArthurDelannoyazerty / merge_dict.py
Created March 29, 2024 15:11
Merge two dict. Keep the dict structure but add the terminal values into a set.
def merge_dict(d1, d2):
"""Merge d2 into d1 with terminal values stored in sets."""
for key, value in d2.items():
if key in d1:
if isinstance(value, dict) and isinstance(d1[key], dict):
merge_dict(d1[key], value)
else:
if not isinstance(d1[key], set):
d1[key] = set([d1[key]])
d1[key].add(value)
@ArthurDelannoyazerty
ArthurDelannoyazerty / xml2dict.py
Created April 3, 2024 11:42
Transform an xml file into a python dict.
import xmltodict
from bs4 import BeautifulSoup
with open(filepath, 'r') as f:
file = f.read()
soup = BeautifulSoup(file, 'xml')
str_xml = str(soup)
dict_xml = xmltodict.parse(str_xml)
@ArthurDelannoyazerty
ArthurDelannoyazerty / count_leaves_dict.py
Last active May 22, 2024 09:57
Count the number of final elements in a dict. This function works for nested dict. Each final value is stored in a list.
def count_leaves_dict(element:dict) -> int:
if isinstance(element, list): return len(element)
if not isinstance(element, dict): raise Exception("Wrong data type")
nb_leaves = 0
for _, value in element.items():
nb_leaves += count_leaves_dict(value)
return nb_leaves
@ArthurDelannoyazerty
ArthurDelannoyazerty / sort_dict.py
Created April 4, 2024 12:44
Sort dict by value.
d_sorted = dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
@ArthurDelannoyazerty
ArthurDelannoyazerty / matplotlib_draw_nested_circles.py
Last active May 14, 2024 12:45
Create matplotlib image of nested circles that represent : 1 - A part of a part of a ... 2 - A path of choice
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from random import random
def draw_path(options:list[int], choices:list[int], margin:int=1, lw:int=7.5, inch:int=5):
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.axis('off')
theta1_limit, theta2_limit = 0, 360
@ArthurDelannoyazerty
ArthurDelannoyazerty / ffmpeg_image_2_video
Last active May 14, 2024 12:45
A windows command line to transform images to a video
ffmpeg -r 24 -i images/%01d.png -vcodec mpeg4 -y movie.mp4
‾‾ ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ ‾‾‾‾‾ ‾‾‾‾‾‾‾‾‾
↑ ↑ ↑ ↑
FPS images format name
@ArthurDelannoyazerty
ArthurDelannoyazerty / tensorboard_torch_histogram.py
Last active April 22, 2024 12:14
Useful code to save pytorch training to tensorboard
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
def save_histograms(writer, step, model):
def flatten_gru_weights(gru_layer):
flattened_weights = []
for param in gru_layer.parameters():
flattened_weights.append(param.data.view(-1))
return torch.cat(flattened_weights)
@ArthurDelannoyazerty
ArthurDelannoyazerty / extract_images_from_tensorboard_log.py
Last active April 19, 2024 14:26 — forked from hysts/extract_images.py
Extract images from Tensorboard log
import pathlib
import numpy as np
import cv2
from tensorboard.backend.event_processing import event_accumulator
event_filepath = 'runs/Apr19_11-02-02_RNSCWL0127/events.out.tfevents.1713517322.RNSCWL0127.15332.0'
output_dir = 'images/img_train'
event_acc = event_accumulator.EventAccumulator(event_filepath, size_guidance={'images': 0})