Posts with tag python

Specify cuda version in setup.py when pip install -e .

2024-11-26
installlangspippython

Specify cuda version in setup.py when pip install -e .see: https://stackoverflow.com/questions/66738473/installing-pytorch-with-cuda-in-setup-pyIn setup function, use something like:"torch@https://download.pytorch.org/whl/cu111/torch-1.8.0%2Bcu111-cp37-cp37m-linux_x86_64.whl", "torchvision@https://download.pytorch.org/whl/cu111/torchvision-0.9.0%2Bcu111-cp37-cp37m-linux_x86_64.wh", "torchaudio@https://download.pytorch.org/whl/torchaudio-0.8.0-cp36-cp36m-linux_x86_64.whl"version links are from: https://download.pytorch.org/whl/torch_stable.htmlmethod above is ok to download, but still failed to build.The following succeeds for building sam-2 with cu118:pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu118 pip install --no-build-isolation -e . # and delete these packages in `setup.py

Plot 3D

2024-08-21
langsmatplotlibpython

Plot 3Dimport matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def d3(tuples): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 解包三元组列表到X, Y, Z坐标 X, Y, Z = zip(*tuples) # 绘制点 ax.scatter(X, Y, Z, color='b') # 绘制线,连接相邻的点 ax.plot(X, Y, Z, color='r') # 设置图表标题和坐标轴标签 ax.set_title('3D Line Plot') ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') ax.set_aspect('auto') max_range = max(max(X) - min(X), max(Y) - min(Y), max(Z) - min(Z)) mid_x = (max(X) + min(X)) * 0.5 mid_y = (max(Y) + min(Y)) * 0.5 mid_z = (max(Z) + min(Z)) * 0.5 ax.set_xlim(mid_x - max_range * 0.5, mid_x + max_range * 0.5) ax.set_ylim(mid_y - max_range * 0.5, mid_y + max_range * 0.5) ax.set_zlim(mid_z - max_range * 0.5, mid_z + max_range * 0.5) # 显示图表 plt.show() # 示例:使用函数绘制图像 with open(sys.argv[1], 'r') as f: ps = [] for line in f: ps.append(tuple(map(float, line.strip().split()[:3]))) d3(ps)

现在 s 就是 '123 + 1234 = 1357' 了,太神奇了

2024-02-05
langspythontutorials

1. 常规读入输出我们常规读入和输出用的是 input() 和 print():n = int(input()) li = list(map(int, input().split())) # 读入一行数,存储到列表 print('Hello world') print(li[0])2. 格式化字符串用 f 作为前缀的字符串可以将其中花括号中的内容自动转换:n = 123 m = 1234 s = f'{n} + {m} = {n + m}' # 现在 s 就是 '123 + 1234 = 1357' 了,太神奇了这种字符串叫做格式化字符串。3. 文件输入输出USACO 比赛中用不上,但是平时可能有用。# 这里新建了一个变量 fin,后面 open 表示打开文件,'1.in' 是文件名,'r' 表示要读入 # 必须保证 1.in 与 python 源文件在同一个文件夹下哦 fin = open('1.in', 'r') # 'w' 表示要输出 fout = open('1.txt', 'w') # 接下来就是把 input() 换成 fin.readline(),从文件中读入 n = int(fin.readline()) li = list(map(int, fin.readline().split())) # 如果要输出到文件,那么可以用格式化字符串 fout.write('Hello world\n') fout.write(f'{li[0]}\n')4. 如何用 USACO test data 自行评测打开形如这样的地址下载题目的 test data,你可以把下面这行的 jan22 改成 dec21 之类的来切换比赛:http://www.usaco.org/index.php?page=jan22results下载完以后解压得到 1.in 1.out 2.in 2.out 等文件。其中 1.in 1.out 表示第一个测试点的输入数据和标准答案。你可以在运行 python 的时候复制粘贴,也可以用文件读入输出。fout = open('1.txt', 'w') # ... 下面输出到 1.txt 中输出到 1.txt 后,你可以在终端使用 diff 命令比较两个文件。diff 1.txt 1.out如果你的答案和标准答案一样,那么 diff 命令不会有任何输出。如果不一样,他就会告诉你哪里不一样,例如:$ diff 2.out 2.txt 1c1 < hello world: 58 --- > hello world: 59 \ No newline at end of fil

输出为 {1, 2},已经自动排序

2024-02-05
langspythontutorials

1. 函数 def func():语法def func(r): # 函数名为 func,这是自定义的 PI = 3.1415926 return r * PI * PI # 函数需要一个返回值,用 return函数可以被多次利用,就像 len() 函数用来求列表长度一样。例题 1写一个函数,求半径为 r 的圆的面积。def S(r): # 求半径为 r 的圆的面积 PI = 3.1415926 return r * PI * PI print(S(5)) # 输出 49.3480203218738例题 2判断一个整数是否是偶数,如果是,返回 True。def even(n): if n % 2 == 0: return True return False # 可以按条件写多条 return 语句2. 集合 set()语法集合可以用来存数据。它和 list 相似,不同的是 set 中数据自动排序,而且不会重复出现。s = set() s.add(2) s.add(2) # 添加元素,但如果已存在就什么都不做 s.add(1) print(s) # 输出为 {1, 2},已经自动排序 s.remove(1) # 删除元素,如果元素不存在,则会发生错误 print(s) # 输出为 {2} s.clear() # 清空元素 print(2 in s) # 判断元素是否在集合中存在,输出为 False你还可以这样创建一个 set:basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) # 输出为 {'orange', 'banana', 'pear', 'apple'}注意:basket = {} 这种写法创建的是一个空的字典,不是一个空的集合。创建空集合应该使用 basket = set()。例题 1输入 $n$ 个数,去掉其中重复的数并从小到大输出,最后输出去重后还剩几个数。n = int(input()) s = set(map(int, input().split())) # 将读入的一行数转换为 set print(*s) # 输出 s 中的所有数字 print(len(s))详细介绍https://www.runoob.com/python3/python3-set.html3. 字典 dict()语法# 创建字典 d1 = { 'abc': 456 } d2 = { 'abc': 123, 98.6: 37 } # 获取字典中对应 key 的值 print(d1['abc']) # 456 print(d2[98.6]) # 37 # 修改字典 d1['abc'] = 123 print(d1['abc']) # 123 # 删除字典元素 del d1['abc'] # 删除一个键 d2.clear() # 清空字典例题 1https://blog.csdn.net/wc19862274581/article/details/124285529问题描述:输入字符串,输出字符串中出现次数最多的字母及其出现次数。如果有多个字母出现次数一样,则按字符从小到大顺序输出字母及其出现次数。输入形式:一个字符串。输出形式:出现次数最多的字母以及其出现次数。样例输入:abcccd样例输出:c 3代码实现:s = input() ma = {} for c in s: if c not in ma: # 如果这个字母没有出现过就初始化为 1 ma[c] = 1 else: # 否则加 1 ma[c] += 1 ans = max(ma.values()) # ma.values() 获取所有的值 # items() 获取所有的键值对,用 sorted() 进行排序后重新用 dict() 重新组成一个有序字典 。这种排序是优先按键排序,其次按值排序 ma = dict(sorted(ma.items())) for c, cnt in ma.items(): if cnt == ans: print(c, cnt)4. 排序 .sort() sorted()ref: https://www.freecodecamp.org/chinese/news/python-sort-how-to-sort-a-list-in-python/a = [2, 1, 3] b = sorted(a) # 不改变 a a.sort() # 改变 a a.sort(reverse=True) # 按特定函数排序 programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"] programming_languages.sort(key=len) programming_languages.sort(key=len, reverse=True) # 按自定义函数排序 programming_languages = [{'language':'Python','year':1991}, {'language':'Swift','year':2014}, {'language':'Java', 'year':1995}, {'language':'C++','year':1985}, {'language':'Go','year':2007}, {'language':'Rust','year':2010}, ] def get_year(element): return element['year'] programming_languages.sort(key=get_year) programming_languages.sort(key=get_year, reverse=True

按自定义函数排序

2024-02-02
base-and-builtinlangspython

ref: https://www.freecodecamp.org/chinese/news/python-sort-how-to-sort-a-list-in-python/a = [2, 1, 3] b = sorted(a) # 不改变 a a.sort() # 改变 a a.sort(reverse=True) # 按自定义函数排序 programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"] programming_languages.sort(key=len) programming_languages.sort(key=len, reverse=True) # 按自定义函数排序 programming_languages = [{'language':'Python','year':1991}, {'language':'Swift','year':2014}, {'language':'Java', 'year':1995}, {'language':'C++','year':1985}, {'language':'Go','year':2007}, {'language':'Rust','year':2010}, ] def get_year(element): return element['year'] programming_languages.sort(key=get_year) programming_languages.sort(key=get_year, reverse=True

allocate-function-error

2024-02-01
langspythontaichi

/home/julyfun/code/taichi-mpm/taichi/external/include/spdlog/fmt/bundled/format.h: In instantiation of ‘void fmt::internal::MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t) [with T = char; long unsigned int SIZE = 500; Allocator = std::allocator<char>; std::size_t = long unsigned int]’: /home/julyfun/code/taichi-mpm/taichi/external/include/spdlog/fmt/bundled/format.h:797:6: required from here /home/julyfun/code/taichi-mpm/taichi/external/include/spdlog/fmt/bundled/format.h:801:30: error: no matching function for call to ‘fmt::internal::MemoryBuffer<char, 500, std::allocator<char> >::allocate(std::size_t&, std::nullptr_t)’ 801 | T *new_ptr = this->allocate(new_capacity, FMT_NULL); | ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~可能你在使用错误环境下的 taichi。检查 .bashrc 之类的配置文件中是否指定了 TAICHI_REPO_DIR 等环境变量,如果指定了,删掉试试,2024-2-1 以此解决

python-debug

2024-01-23
debugpythonsoftwares-and-toolsvscode

This method is verified!https://code.visualstudio.com/docs/python/debugginghttps://stackoverflow.com/questions/51244223/visual-studio-code-how-debug-python-script-with-arguments开始vscode cmd: show run and debug.click 'create launch.json'A file is created.If you wanna run shell script for python like this:CUDA_VISIBLE_DEVICES=0 python cloth_funnels/run_sim.py \ name="demo-single" \ load=models/longsleeve_canonicalized_alignment.pth \ eval_tasks=assets/tasks/longsleeve-single.hdf5 \ eval=True \ num_processes=1 \ episode_length=10 \ wandb=disabled \ fold_finish=True \ dump_visualizations=True Add args like, [tested ok]:{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: 当前文件", "type": "python", "request": "launch", "program": "${file}", // "program": "${workspaceFolder}/script/eval_policy.py", // 这样也行 "console": "integratedTerminal", "args": ["name=\"demo-single\"", "load=models/longsleeve_canonicalized_alignment.pth", "eval_tasks=assets/tasks/longsleeve-single.hdf5", "eval=True", "num_processes=1", "episode_length=10", "wandb=disabled", "fold_finish=True", "dump_visualizations=True"], "env": { "CUDA_VISIBLE_DEVICES": "0", "HYDRA_FULL_ERROR": "1", }, } ] }Switch to the file you want to run (as in launch.json we by default designate "Run current file", so you have to switch to the exact file to run).Add a breakpoint,Click the green delta in "Run python and debug" menu,Everything is well! And watch params in the menu!RemoteUsing vscode-ssh is also ok to run python debug in remote machine

libGL-error-MESA-LOADER-failed-to-open-iris-usr-lib-dri-iris_dri-so

2024-01-22
langspython

libGL error: failed to load driver: iris libGL error: MESA-LOADER: failed to open iris: /usr/lib/dri/iris_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri) libGL error: failed to load driver: iris libGL error: MESA-LOADER: failed to open swrast: /usr/lib/dri/swrast_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri) libGL error: failed to load driver: swrast 2024-01-22 18:06:31.038 ( 26.810s) [ 7F77B303A740]vtkXOpenGLRenderWindow.:651 ERR| vtkXOpenGLRenderWindow (0x77ecfd0): Cannot create GLX context. Aborting.https://stackoverflow.com/questions/72110384/libgl-error-mesa-loader-failed-to-open-irisOn Ubuntu 22.04, 24-1-22, python 3.11, using conda, taichi:conda install -c conda-forge libstdcxx-ng this fixes the erro

Add the parent directory to the Python path

2024-01-15
langspythonworkspace

对于一个项目,你执行 python somewhere/main.py则 main.py 运行的所有东西,包括 main.py import 的 py,其中的 import 的 sys.path(sys.path 会决定 import 的位置) 均为 somewhere/(即 main.py 所在的位置)。例如 main.py 中 from pkg1.animal import eat, animal.py 有 from mantis import something,则 mantis 必须在 main.py 所在文件夹下,不可以在 pkg1/ 中。但是 vscode 的智能提示比较呆,当前文件 init.py 的祖先文件夹都会自动加入智能提示的 sys.path.other solutions你也可以 from .somedir import xxx[what] 这啥玩意sys.path.append 的作用范围?cur_dir = os.path.dirname(__file__) print(cur_dir) # Add the parent directory to the Python path sys.path.append(cur_dir) print(sys.path, type(sys.path))该语句后所有的 import (就算 import 文件中的 import 也可以)都会用这个新的 path.注意 import 后不再能文件夹寻址如果有 plant/apple/eat.py你可以 import plant.apple.eat.some但不可以 import plant 之后再 a = plant.apple.eat.some(

networkx

2024-01-15
langspython

this package works together with matplotlib.import networkx as nx from matplotlib import pyplot as plt g = nx.Graph() g.add_node(1) list(g.nodes()) g.add_nodes_from([3, 4]) print(g.nodes) nx.draw(g) nx.draw(g, with_labels=True) plt.show() g.add_node('coin') g.add_edge(1, 2) e = (2, 3) g.add_edge(*e) g.add_edges_from([(1, 3), (1, 4), (1, 5)]) G.remove_node(2) G.remove_nodes_from([4, 5, H, 'coin']) print("les sommets de G sont : ", G.nodes) edgelist = [(0, 1), (1, 2), (2, 3)] I = nx.Graph(edgelist) edgelist1 = [(0, 1), (0, 2), (0, 3)] edgelist2 = [(0, 4), (0, 5), (0, 6)] G1 = nx.Graph(edgelist1) G2 = nx.Graph(edgelist2) H1 = nx.disjoint_union(G1, G2) # make two graph in the same one H2 = nx.compose(G1, G2) # make the same considering the node id g = nx.petersen_graph() # a special graph nx.draw_shell(g, nlist=[range(5, 10), range(5)]) # make 0, 1, 2, 3, 4 in a shell options = { 'node_color': 'yellow', 'node_size': 500, 'width': 2, 'with_labels': True } nx.draw_random(G, **options) plt.show() nx.draw_circular(G, **options) plt.show() nx.draw_shell(G, nlist=[range(5, 10), range(5)], **options) plt.show() nx.draw(G) plt.savefig("graph.png") G2= nx.DiGraph () G2.add_edges_from([(0, 1),(1,0), (0, 2), (0, 3)]) nx.draw_random(G2, with_labels=True, font_weight='bold') plt.show()draw in particular positionG=nx.Graph() G.add_edges_from([[1,2],[2,3],[3,1]]) position={1:[0,2],2:[2,0],3:[0,0]} #dictionnaire où on précise les coordonnées de chacun des sommets nx.draw(G,pos=position

runtime-error-attemp-to-start-a-new-process-before-the-current-process

2024-01-15
langsmultiprocessingpython

RuntimeError: Attempt to start a new process before the current process has finished its bootstrapping phase. This probably means that you are on Windows and you have forgotten to use the proper idiom in the main module: if name == 'main': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce a Windows executable.SolutionAs the note said, add __main__`` guard and add freeze_support()` and the begining.if __name__ == "__main__": # multiprocessing.freeze_support() # may be not needed start = time.time() ...Ref:https://discuss.pytorch.org/t/runtimeerror-an-attempt-has-been-made-to-start-a-new-process-before-the-current-process-has-finished-its-bootstrapping-phase/145462/

Sample image tensor dimensions: (channels=3, height=100, width=100)

2024-01-15
langspythonpytorch

ChatGPTimport cv2 import numpy as np import torch # Sample image tensor dimensions: (channels=3, height=100, width=100) image_tensor = torch.rand(3, 100, 100) # Replace with your actual tensor # Convert PyTorch tensor to NumPy array image_np = image_tensor.permute(1, 2, 0).cpu().numpy() # Channels last for OpenCV # Define the target size target_height = 64 target_width = 64 # Resize the image using OpenCV resized_image_np = cv2.resize(image_np, (target_width, target_height)) # Convert NumPy array back to PyTorch tensor resized_image_tensor = torch.from_numpy(resized_image_np).permute(2, 0, 1).float() # Print the shapes to verify print("Original tensor shape:", image_tensor.shape) print("Resized tensor shape:", resized_image_tensor.shape)import torch import torch.nn.functional as F # 假设你有一个480x480的RGB图片,可以表示为一个3维的torch.Tensor # 假设img是你的原始图像,大小为(1, 3, 480, 480) # (1, 3, 480, 480)表示(batch_size, channels, height, width) # 生成一个480x480的假图片,这里用随机数代替 img = torch.rand(1, 3, 480, 480) # 缩放成128x128的图像 scaled_img = F.interpolate(img, size=(128, 128), mode='bilinear', align_corners=False) # 输出缩放后图像的大小 print("缩放后图像大小:", scaled_img.size()) # 输出: torch.Size([1, 3, 128, 128]

No more posts to load.