crossfile_context_retrievalwref dict | prompt stringlengths 252 32.6k | right_context stringlengths 0 81.2k | metadata dict | crossfile_context_retrieval dict | groundtruth stringlengths 5 208 |
|---|---|---|---|---|---|
{
"list": [
{
"filename": "tests/metrics.py",
"retrieved_chunk": "from bhv.np import NumPyPacked64BHV as BHV\na = BHV.rand()\nfor i in range(0, 21):\n p = i/20\n b = a.flip_frac(p)\n print(p)\n print(\"ber\", 1. - a.bit_error_rate(b))\n print(\"cos\", a.cosine(b))\n print(\"jac\", a.... | import unittest
# import torch
# from bhv.np import NumPyPacked64BHV as BHV
from bhv.vanilla import VanillaBHV as BHV
DELTA = 0.015
class TestComposites(unittest.TestCase):
def test_flip_frac_on(self):
# self | BHV.random(flip_on_frac)
r = BHV.rand()
self.assertLessEqual(r.zscore(), 4,... |
def test_flip_pow_on(self):
# self | ~BHV.rand2(flip_on_pow)
r = BHV.rand()
self.assertLessEqual(r.zscore(), 4, "rerun test")
for pow in range(20):
tweaked = r.flip_pow_on(pow)
expected = 2**(-pow - 2)
self.assertAlmostEqual(tweaked.bit_error_ra... | {
"context_start_lineno": 0,
"file": "tests/composites.py",
"groundtruth_start_lineno": 26,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 27,
"task_id": "project_cc_python/6379"
} | {
"list": [
{
"filename": "tests/metrics.py",
"retrieved_chunk": " print(\"tve\", a.tversky(b, .5, .5))",
"score": 50.40355460295095
},
{
"filename": "tests/fiestal.py",
"retrieved_chunk": " ks = BHV.nrand(10)\n x_enc_k = [x.feistal(k) for k in ks]\n x... | ZERO.flip_frac_on(k).active_fraction(), k, delta=DELTA) |
{
"list": [
{
"filename": "benchmarks/lookup.py",
"retrieved_chunk": "deviations = [0, 1, 2, 4]\nsizes = [20, 1000]\n# e.g.\n# hvs=[10, 20, 30, 50, 100]\n# v=20 + 5\n# threshold=10\n# returns 20, 30\nindex_times = {s: [] for s in sizes}\nlookup_times = {s: {t: [] for t in thresholds} for s in sizes}\n... | # Majority of a various number of inputs
from bhv import DIMENSION, AbstractBHV
# from bhv.np import NumPyPacked64BHV as BHV
# from bhv.np import NumPyBoolBHV as BHV
from bhv.native import CNativePackedBHV as BHV
from time import monotonic
from statistics import pstdev, fmean
repeat_pipeline = 5
sizes = list(range(... |
for i in range(repeat_pipeline):
print(f"repetition {i + 1}/{repeat_pipeline}")
for size in sizes:
s = rs[:size]
t_exec = monotonic()
maj = BHV.majority(s)
execution_times[size].append(monotonic() - t_exec)
distances[size].append(fmean(AbstractBHV.frac_to_std(r.hamm... | {
"context_start_lineno": 0,
"file": "benchmarks/majority.py",
"groundtruth_start_lineno": 21,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 22,
"task_id": "project_cc_python/6345"
} | {
"list": [
{
"filename": "benchmarks/lookup.py",
"retrieved_chunk": "for _ in range(repeat_pipeline):\n for size in sizes:\n rs = BHV.nrand(size)\n ps = {deviation: [r.flip_frac(BHV.std_to_frac(deviation))\n for r in sample(rs, repeat_lookup)]\n ... | rand() for _ in range(1000001)] |
{
"list": [
{
"filename": "bhv/visualization.py",
"retrieved_chunk": "from .abstract import AbstractBHV, DIMENSION\nclass DistanceGraph:\n @classmethod\n def from_scope(cls, local_dict):\n return cls(*zip(*[(v, k) for k, v in local_dict.items() if isinstance(v, AbstractBHV)]))\n def __... | from .abstract import AbstractBHV
from typing import TypeVar, Generic, Iterable, Iterator, Optional, Mapping
from math import comb
K = TypeVar("K")
class Store(Generic[K]):
@classmethod
def auto_associative(cls, vs: Iterable[AbstractBHV]) -> 'Store[int]':
return cls(dict(enumerate(vs)))
def __i... |
# expected number of bits flipped compared to the majority of N random hvs
# E[bit_error_rate(v, MAJ(v, v_0, ..v_n))]
# E[v_q != MAJ(v, v_0, ..v_n)_q] WLOG
# E[1_q != MAJ(1, v_0, ..v_n)_q]
# E[1 != MAJ(1, v_0, ..v_n)_q]
# PoiBin(1, af(v_0), ..af(v_n)).cdf(n//2)
# further assuming af(v_0) ==... | {
"context_start_lineno": 0,
"file": "bhv/lookup.py",
"groundtruth_start_lineno": 49,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 50,
"task_id": "project_cc_python/6343"
} | {
"list": [
{
"filename": "bhv/symbolic.py",
"retrieved_chunk": " return cls.ONE if t[0] else cls.ZERO\n @classmethod\n def synth_af(cls, af: float, depth=1, v_gen=lambda x: Rand(x), threshold=1e-6):\n assert 0. < af < 1.\n d = af - (1 / 2) ** depth\n v = v_gen(de... | frac_to_std(AbstractBHV.maj_ber(self.bundle_size)) |
{
"list": [
{
"filename": "examples/viz_distances.py",
"retrieved_chunk": "from bhv.vanilla import VanillaBHV as BHV\nfrom bhv.visualization import DistanceGraph\na, b, c, d = BHV.nrand(4)\nabc = BHV.majority([a, b, c])\na1 = a.flip_frac_on(.1)\na0 = a.flip_frac_off(.1)\ncq = c.select(a0, a1)\nb_d = b... | import unittest
from bhv.np import NumPyPacked64BHV as BHV
from bhv.embedding import Random, InterpolateBetween
class TestRandomEmbedding(unittest.TestCase):
def test_random(self):
a, b, c = "abc"
embedding = Random(BHV)
hva = embedding.forward(a)
hvb = embedding.forward(b)
... |
self.assertEqual(b, embedding.back(hvb))
class TestInterpolateLineEmbedding(unittest.TestCase):
def test_internal(self):
embedding = InterpolateBetween(BHV)
a, b, c = .1, .5, .68
self.assertAlmostEqual(a, embedding.back(embedding.forward(a)), 2)
if __name__ == '__main__':
u... | {
"context_start_lineno": 0,
"file": "tests/embedding.py",
"groundtruth_start_lineno": 17,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 18,
"task_id": "project_cc_python/6366"
} | {
"list": [
{
"filename": "examples/viz_distances.py",
"retrieved_chunk": "from bhv.vanilla import VanillaBHV as BHV\nfrom bhv.visualization import DistanceGraph\na, b, c, d = BHV.nrand(4)\nabc = BHV.majority([a, b, c])\na1 = a.flip_frac_on(.1)\na0 = a.flip_frac_off(.1)\ncq = c.select(a0, a1)\nb_d = b... | back(hvq)) |
{
"list": [
{
"filename": "nodes/crop.py",
"retrieved_chunk": " if bbox != None:\n x, y, width, height = bbox\n cropped_image = image[:, y : y + height, x : x + width, :]\n cropped_mask = mask[y : y + height, x : x + width] if mask != None else None\n crop_data =... | import torch
import torchvision.transforms.functional as TF
from ..utils import log, hex_to_rgb, tensor2pil, pil2tensor
from math import sqrt, ceil
from typing import cast
from PIL import Image
class TransformImage:
"""Save torch tensors (image, mask or latent) to disk, useful to debug things outside comfy
... |
if image.size(0) == 0:
return (torch.zeros(0),)
transformed_images = []
frames_count, frame_height, frame_width, frame_channel_count = image.size()
new_height, new_width = int(frame_height * zoom), int(frame_width * zoom)
log.debug(f"New height: {new_height}, New ... | {
"context_start_lineno": 0,
"file": "nodes/transform.py",
"groundtruth_start_lineno": 55,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 56,
"task_id": "project_cc_python/6432"
} | {
"list": [
{
"filename": "nodes/number.py",
"retrieved_chunk": " RETURN_TYPES = (\"NUMBER\",)\n FUNCTION = \"float_to_number\"\n CATEGORY = \"mtb/number\"\n def float_to_number(self, float):\n return (float,)\n return (int,)\n__nodes__ = [\n FloatToNumber,\n IntToBool,... | debug(f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear}") |
{
"list": [
{
"filename": "bhv/pytorch.py",
"retrieved_chunk": " def permute_words(self, permutation: TorchWordPermutation) -> 'TorchPackedBHV':\n return TorchPackedBHV(self.data[permutation.data])\n def permute(self, permutation_id: 'int | tuple[int, ...]') -> 'TorchPackedBHV':\n ... | import unittest
import torch
from bhv.pytorch import TorchPackedBHV, TorchBoolBHV
class TestTorchBoolBHV(unittest.TestCase):
def test_basic(self):
self.assertTrue(True)
class TestTorchBHVConversion(unittest.TestCase):
def test_random(self):
rp = TorchPackedBHV.rand()
self.assertTru... |
self.assertTrue(torch.equal(TorchPackedBHV.ZERO.data, TorchBoolBHV.ZERO.pack().data))
self.assertTrue(torch.equal(TorchPackedBHV.ONE.unpack().data, TorchBoolBHV.ONE.data))
self.assertTrue(torch.equal(TorchPackedBHV.ONE.data, TorchBoolBHV.ONE.pack().data))
if __name__ == '__main__':
unitte... | {
"context_start_lineno": 0,
"file": "tests/test_pytorch.py",
"groundtruth_start_lineno": 20,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 21,
"task_id": "project_cc_python/6391"
} | {
"list": [
{
"filename": "bhv/pytorch.py",
"retrieved_chunk": " def __xor__(self, other: 'TorchPackedBHV') -> 'TorchPackedBHV':\n return TorchPackedBHV(torch.bitwise_xor(self.data, other.data))\n def __and__(self, other: 'TorchPackedBHV') -> 'TorchPackedBHV':\n return TorchPackedB... | ZERO.unpack().data, TorchBoolBHV.ZERO.data)) |
{
"list": [
{
"filename": "nodes/crop.py",
"retrieved_chunk": " # Convert the image to a NumPy array\n imgs = tensor2np(image)\n out = []\n for img in imgs:\n # Crop the image from the bounding box\n img = img[min_y:max_y, min_x... | from gfpgan import GFPGANer
import cv2
import numpy as np
import os
from pathlib import Path
import folder_paths
from ..utils import pil2tensor, np2tensor, tensor2np
from basicsr.utils import imwrite
from PIL import Image
import torch
from ..log import NullWriter, log
from comfy import model_management
import comfy
... |
pbar = comfy.utils.ProgressBar(steps)
s = comfy.utils.tiled_scale(
imgt,
lambda a: self.upscale_model(a),
tile_x=tile,
tile_y=tile,
overlap=overlap,
upscale_amount=self.upscale_model.scale,
pbar=pbar,
)
... | {
"context_start_lineno": 0,
"file": "nodes/faceenhance.py",
"groundtruth_start_lineno": 128,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 129,
"task_id": "project_cc_python/6424"
} | {
"list": [
{
"filename": "nodes/deep_bump.py",
"retrieved_chunk": " \"\"\"Performs row by row 1D convolutions of the given 2D image with the given 1D kernel.\"\"\"\n # Input kernel length must be odd\n k_l = len(kernel_1d)\n assert k_l % 2 != 0\n # Convolution is repeat-padded\n ext... | debug(f"Steps: {steps}") |
{
"list": [
{
"filename": "bhv/symbolic.py",
"retrieved_chunk": " return BiasRel(rel, l, r)\n def show(self, **kwargs):\n return f\"{self.l.show(**kwargs)}.bias_rel({self.r.show(**kwargs)}, {self.rel.show(**kwargs)})\"\n def instantiate(self, **kwargs):\n return self.l.execu... | # Let's try and encode some rules, and do some rule-based computing
# If x is the mother of y and y is the father of z then x is the grandmother of z
# from bhv.np import NumPyPacked64BHV as BHV, NumPyWordPermutation as Perm
from bhv.vanilla import VanillaBHV as BHV, VanillaPermutation as Perm
# relation utility
rel_... |
# our rule, read `xor` as "implied by" and `BHV.majority` as "and"
# note this is applied to multiple "datapoints" ...
def generate_sample():
person_x = BHV.rand()
person_y = BHV.rand()
person_z = BHV.rand()
mxy = apply_rel(mother_of, person_x, person_y)
fyz = apply_rel(father_of, person_y, person_z)
gxz... | {
"context_start_lineno": 0,
"file": "examples/grandmother_example.py",
"groundtruth_start_lineno": 26,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 27,
"task_id": "project_cc_python/6406"
} | {
"list": [
{
"filename": "bhv/symbolic.py",
"retrieved_chunk": " def reconstruct(self, l, r):\n return Related(l, r, self.stdvs)\n def show(self, **kwargs):\n return f\"{self.l.show(**kwargs)}.related({self.r.show(**kwargs)}, {self.stdvs})\"\n def instantiate(self, **kwargs):\n... | majority([sx, sy]) |
{
"list": [
{
"filename": "nodes/faceenhance.py",
"retrieved_chunk": " )\n sys.stdout = sys.__stdout__\n log.warning(f\"Weight value has no effect for now. (value: {weight})\")\n if save_tmp_steps:\n self.save_intermediate_images(cropped_faces, restored_faces, he... | # region imports
import onnxruntime
from pathlib import Path
from PIL import Image
from typing import List, Set, Union, Optional
import cv2
import folder_paths
import glob
import insightface
import numpy as np
import os
import torch
from insightface.model_zoo.inswapper import INSwapper
from ..utils import pil2tensor, t... |
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
else:
log.warning("No source face found")
else:
log.error("No face swap model provided")
return result_image
# endregion face swap utils
__nodes__ = [FaceSwap, LoadFaceSwapModel, LoadFaceAnalysi... | {
"context_start_lineno": 0,
"file": "nodes/faceswap.py",
"groundtruth_start_lineno": 219,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 220,
"task_id": "project_cc_python/6430"
} | {
"list": [
{
"filename": "install.py",
"retrieved_chunk": " print(\n \" \" * len(encoded_header)\n if kwargs.get(\"no_header\")\n else apply_color(apply_format(encoded_header, \"bold\"), color=\"yellow\"),\n encoded_text,\n file=file,\n )\n# endregion\n# regio... | warning(f"No target face found for {face_num}") |
{
"list": [
{
"filename": "nodes/faceswap.py",
"retrieved_chunk": " FUNCTION = \"load_model\"\n CATEGORY = \"mtb/facetools\"\n def load_model(self, faceswap_model: str):\n model_path = os.path.join(\n folder_paths.models_dir, \"insightface\", faceswap_model\n )\n ... | import os
import re
import torch
import numpy as np
import hashlib
from PIL import Image, ImageOps
from PIL.PngImagePlugin import PngInfo
import folder_paths
from pathlib import Path
import json
from ..log import log
class LoadImageSequence:
"""Load an image sequence from a folder. The current frame is used to d... |
frames = resolve_all_frames(path)
log.debug(f"Found {len(frames)} frames")
imgs = []
masks = []
for frame in frames:
img, mask = img_from_path(frame)
imgs.append(img)
masks.append(mask)
out_img = ... | {
"context_start_lineno": 0,
"file": "nodes/video.py",
"groundtruth_start_lineno": 50,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 51,
"task_id": "project_cc_python/6427"
} | {
"list": [
{
"filename": "nodes/crop.py",
"retrieved_chunk": " # f\"Batch count mismatch for mask and image, it can either be 1 mask for X images, or X masks for X images (mask: {mask.shape} | image: {image.shape})\"\n # )\n _mask = tensor2pil(1.0 - ma... | debug(f"Loading all frames from {path}") |
{
"list": [
{
"filename": "tests/unit/decodable/config/test_profile_reader.py",
"retrieved_chunk": "TEST_PROFILE_ACCESS_TOKEN = \"yyy\"\nclass TestProfileAdapter:\n \"\"\"Test getting profile name from env variable\"\"\"\n @mock.patch.dict(os.environ, {PROFILE_ENV_VARIABLE_NAME: \"test\"})\n ... | #
# Copyright 2023 decodable Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
if profile_name not in profile_access_tokens.profile_tokens:
raise Exception(
f"Undefined '{profile_name} in decodable profile file ~/.decodable/auth"
)
access_token = profile_access_tokens.profile_tokens[profile_name]
return DecodableApiClient(
... | {
"context_start_lineno": 0,
"file": "decodable/client/client_factory.py",
"groundtruth_start_lineno": 31,
"repository": "decodableco-dbt-decodable-8ef941c",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/6326"
} | {
"list": [
{
"filename": "dbt/adapters/decodable/connections.py",
"retrieved_chunk": " )\n decodable_connection_test = client.test_connection()\n if not decodable_connection_test.ok:\n error_message = \"\"\n if (\n decodable_connection_test.re... | load_profiles() |
{
"list": [
{
"filename": "tests/marshalling.py",
"retrieved_chunk": " t0 = monotonic_ns()\n rs_ = Image.load_pbm(f, impl, binary=True).hvs\n print(\" deserializing\", monotonic_ns() - t0)\n assert len(rs) == len(rs_)\n for r, r_ in zip(rs, rs_):\n assert r == r_\n ... | from time import monotonic_ns
# from bhv.np import NumPyBoolBHV as BHV
from bhv.np import NumPyPacked64BHV as BHV
# from bhv.native import CNativePackedBHV as BHV
x = 0x7834d688d8827099
for i in range(5000000):
x = x + (x % 7)
N = 201
t0 = monotonic_ns()
rs = [BHV.rand() for _ in range(N)]
t1 = monotonic_ns()... |
t5 = monotonic_ns()
print("hamming", t5 - t4)
print(sum(qs)/N)
| {
"context_start_lineno": 0,
"file": "tests/native_test.py",
"groundtruth_start_lineno": 46,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 47,
"task_id": "project_cc_python/6385"
} | {
"list": [
{
"filename": "tests/marshalling.py",
"retrieved_chunk": " print(\" serializing\", monotonic_ns() - t0)\n string = f.getvalue()\n with io.StringIO(string) as f:\n t0 = monotonic_ns()\n rs_ = Image.load_pbm(f, impl, binary=False).hvs\n print(\" deseri... | hamming(r, m) for r in rs] |
{
"list": [
{
"filename": "nodes/generate.py",
"retrieved_chunk": " fill_color = (0, 0, 0) if invert else (255, 255, 255)\n code = img = qr.make_image(back_color=back_color, fill_color=fill_color)\n # that we now resize without filtering\n code = code.resize((width, height)... | import torch
from ..utils import tensor2pil, pil2tensor, tensor2np, np2tensor
from PIL import Image, ImageFilter, ImageDraw, ImageChops
import numpy as np
from ..log import log
class Bbox:
"""The bounding box (BBOX) custom type used by other nodes"""
@classmethod
def INPUT_TYPES(cls):
return {
... |
return new_bbox
def bbox_to_region(bbox, target_size=None):
bbox = bbox_check(bbox, target_size)
# to region
return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3])
class Uncrop:
"""Uncrops an image to a given bounding box
The bounding box can be given as a tuple of (x, y, width,... | {
"context_start_lineno": 0,
"file": "nodes/crop.py",
"groundtruth_start_lineno": 180,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 181,
"task_id": "project_cc_python/6435"
} | {
"list": [
{
"filename": "nodes/generate.py",
"retrieved_chunk": "class TextToImage:\n \"\"\"Utils to convert text to image using a font\n The tool looks for any .ttf file in the Comfy folder hierarchy.\n \"\"\"\n fonts = {}\n def __init__(self):\n # - This is executed when the ... | warn(f"BBox too big, constrained to {new_bbox}") |
{
"list": [
{
"filename": "nodes/video.py",
"retrieved_chunk": " load_all = current_frame == -1\n if load_all:\n log.debug(f\"Loading all frames from {path}\")\n frames = resolve_all_frames(path)\n log.debug(f\"Found {len(frames)} frames\")\n i... | import torch
from ..utils import tensor2pil, pil2tensor, tensor2np, np2tensor
from PIL import Image, ImageFilter, ImageDraw, ImageChops
import numpy as np
from ..log import log
class Bbox:
"""The bounding box (BBOX) custom type used by other nodes"""
@classmethod
def INPUT_TYPES(cls):
return {
... |
out.append(img)
image = np2tensor(out)
log.debug(f"Cropped images shape: {image.shape}")
bounding_box = (min_x, min_y, max_x - min_x, max_y - min_y)
return (
bounding_box,
image,
)
class Crop:
"""Crops an image and an option... | {
"context_start_lineno": 0,
"file": "nodes/crop.py",
"groundtruth_start_lineno": 93,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 94,
"task_id": "project_cc_python/6433"
} | {
"list": [
{
"filename": "nodes/video.py",
"retrieved_chunk": " )\ndef resolve_all_frames(pattern):\n folder_path, file_pattern = os.path.split(pattern)\n log.debug(f\"Resolving all frames in {folder_path}\")\n frames = []\n hash_count = file_pattern.count(\"#\")\n frame_pattern = r... | debug(f"Cropped image to shape {img.shape}") |
{
"list": [
{
"filename": "test/icp.py",
"retrieved_chunk": " That_rl = LieGroup(\"{\\\\hat{T}_{rl}}\")\n d = LieAlgebra(\"{\\\\delta}\")\n e = n_ri.transpose() * ((exp(d) * That_rl * l_i) - r_i)\n e = e.subs(That_rl * l_i, rhat_i)\n f = TotalFunction(e)\n df_dd = f.diff(d)\n # Co... | import pytest, sys
sys.path.append('..')
from sympy import expand, symbols, Matrix, tensorcontraction
from SymE3.core import Pixel, PointH, LieGroup, LieAlgebra, CustomFunction, SymbolicFunction, dehom, TotalFunction, exp
from SymE3.detail import _MatrixSym
def test_photometric_alignment():
x_i = Pixel("{x_i}")
... |
il = I_l.__explicit__()(x[0], x[1])
ir = I_r.__explicit__()(pi[0], pi[1])
fe = f.as_explicit()
c = ir - il
assert c.__str__() == fe.__str__()
dpi_dph = tensorcontraction(pi.diff(ph), (1, 3)).transpose()
dir_dpi = Matrix([ir.fdiff(1), ir.fdiff(2)]).transpose()
gradpi = dir_dpi * dpi_dp... | {
"context_start_lineno": 0,
"file": "test/photo.py",
"groundtruth_start_lineno": 34,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/6447"
} | {
"list": [
{
"filename": "test/icp.py",
"retrieved_chunk": " c = nr.transpose() * (rh - r)\n fe = f.as_explicit()\n assert c == fe.tomatrix()\n cp = rh.cross(nr).transpose()\n jc = nr.transpose()\n jc = jc.col_insert(3, cp)\n assert jc == df_dd",
"score": 89.53964877576985
... | __explicit__()(ph).tomatrix() |
{
"list": [
{
"filename": "nodes/image_interpolation.py",
"retrieved_chunk": " for frame in util.interpolate_recursively_from_memory(\n in_frames, interpolate, film_model\n ):\n out_tensors.append(\n torch.from_numpy(frame) if isinstance(frame, np.nda... | from ..log import log
class AnimationBuilder:
"""Convenient way to manage basic animation maths at the core of many of my workflows"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"total_frames": ("INT", {"default": 100, "min": 0}),
# "fps"... |
return (frame, scaled, raw_loop, (frame == (total_frames - 1)))
__nodes__ = [AnimationBuilder]
| {
"context_start_lineno": 0,
"file": "nodes/animation.py",
"groundtruth_start_lineno": 38,
"repository": "melMass-comfy_mtb-3b07984",
"right_context_start_lineno": 39,
"task_id": "project_cc_python/6436"
} | {
"list": [
{
"filename": "nodes/image_interpolation.py",
"retrieved_chunk": " log.debug(f\"Output shape {out_tensors.shape}\")\n log.debug(f\"Output type {out_tensors.dtype}\")\n return (out_tensors,)\nclass ConcatImages:\n \"\"\"Add images to batch\"\"\"\n RETURN_TYPES = (... | debug(f"frame: {frame}/{total_frames} scaled: {scaled}") |
{
"list": [
{
"filename": "test/icp.py",
"retrieved_chunk": " That_rl = LieGroup(\"{\\\\hat{T}_{rl}}\")\n d = LieAlgebra(\"{\\\\delta}\")\n e = n_ri.transpose() * ((exp(d) * That_rl * l_i) - r_i)\n e = e.subs(That_rl * l_i, rhat_i)\n f = TotalFunction(e)\n df_dd = f.diff(d)\n # Co... | import pytest, sys
sys.path.append('..')
from sympy import expand, symbols, Matrix, tensorcontraction
from SymE3.core import Pixel, PointH, LieGroup, LieAlgebra, CustomFunction, SymbolicFunction, dehom, TotalFunction, exp
from SymE3.detail import _MatrixSym
def test_photometric_alignment():
x_i = Pixel("{x_i}")
... |
ir = I_r.__explicit__()(pi[0], pi[1])
fe = f.as_explicit()
c = ir - il
assert c.__str__() == fe.__str__()
dpi_dph = tensorcontraction(pi.diff(ph), (1, 3)).transpose()
dir_dpi = Matrix([ir.fdiff(1), ir.fdiff(2)]).transpose()
gradpi = dir_dpi * dpi_dph
cp = ph.cross(gradpi).transpose()
... | {
"context_start_lineno": 0,
"file": "test/photo.py",
"groundtruth_start_lineno": 35,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 36,
"task_id": "project_cc_python/6448"
} | {
"list": [
{
"filename": "test/icp.py",
"retrieved_chunk": " c = nr.transpose() * (rh - r)\n fe = f.as_explicit()\n assert c == fe.tomatrix()\n cp = rh.cross(nr).transpose()\n jc = nr.transpose()\n jc = jc.col_insert(3, cp)\n assert jc == df_dd",
"score": 89.34705894862847
... | __explicit__()(x[0], x[1]) |
{
"list": [
{
"filename": "test/icp.py",
"retrieved_chunk": " That_rl = LieGroup(\"{\\\\hat{T}_{rl}}\")\n d = LieAlgebra(\"{\\\\delta}\")\n e = n_ri.transpose() * ((exp(d) * That_rl * l_i) - r_i)\n e = e.subs(That_rl * l_i, rhat_i)\n f = TotalFunction(e)\n df_dd = f.diff(d)\n # Co... | import pytest, sys
sys.path.append('..')
from sympy import Matrix
from SymE3.core import PointH, LieGroup, LieAlgebra, SymbolicFunction, dehom, TotalFunction, exp
from SymE3.detail import _MatrixSym
def test_sdf():
l_i = PointH("{l_i}")
lhat_i = PointH("{\\hat{l}_i}")
That_wl = LieGroup("{\\hat{T}_{wl}}"... |
fe = f.as_explicit()
c = ps
assert c.__str__() == fe.__str__()
dpsi_dlh = Matrix([ps.fdiff(1), ps.fdiff(2), ps.fdiff(3)]).transpose()
cp = lh.cross(dpsi_dlh).transpose()
jc = dpsi_dlh
jc = jc.col_insert(3, cp)
assert jc == df_dd
| {
"context_start_lineno": 0,
"file": "test/sdf.py",
"groundtruth_start_lineno": 23,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 24,
"task_id": "project_cc_python/6441"
} | {
"list": [
{
"filename": "test/icp.py",
"retrieved_chunk": " c = nr.transpose() * (rh - r)\n fe = f.as_explicit()\n assert c == fe.tomatrix()\n cp = rh.cross(nr).transpose()\n jc = nr.transpose()\n jc = jc.col_insert(3, cp)\n assert jc == df_dd",
"score": 98.96305255858364
... | __explicit__()(lh[0], lh[1], lh[2]) |
{
"list": [
{
"filename": "examples/grandmother_example.py",
"retrieved_chunk": "# Let's try and encode some rules, and do some rule-based computing\n# If x is the mother of y and y is the father of z then x is the grandmother of z\n# from bhv.np import NumPyPacked64BHV as BHV, NumPyWordPermutation as... | from bhv.symbolic import SymbolicBHV, Var
from bhv.np import NumPyBoolBHV as BHV, DIMENSION
from bhv.visualization import Image
import numpy as np
def make_rule(r: int):
mask = [b == '1' for b in bin(r)[2:].rjust(8, "0")]
formula = SymbolicBHV.synth([Var("left"), Var("center"), Var("right")], mask)
formul... |
# single on bit
# initial = np.zeros(DIMENSION, dtype=np.bool_)
# initial[64] = np.bool_(1)
# last_v = BHV(initial)
vs = [last_v]
for i in range(ITERATIONS):
vs.append(rule(vs[-1]))
with open(f"rule{RULE}.pbm", 'wb') as f:
Image(vs).pbm(f, binary=True)
| {
"context_start_lineno": 0,
"file": "examples/ca_rules.py",
"groundtruth_start_lineno": 23,
"repository": "Adam-Vandervorst-PyBHV-ff5dcca",
"right_context_start_lineno": 24,
"task_id": "project_cc_python/6399"
} | {
"list": [
{
"filename": "tests/lsynthesis.py",
"retrieved_chunk": "print(tos(110, 8), BHV.synth(names, tomask(tos(110, 8))).simplify().show())\nprint(tos(90, 8), BHV.synth(names, tomask(tos(90, 8))).simplify().show())\nprint(tos(30, 8), BHV.synth(names, tomask(tos(30, 8))).simplify().show())\nprint(... | random(.03) |
{
"list": [
{
"filename": "test/bundle.py",
"retrieved_chunk": " def proj(p):\n p_ray = p / p[2, 0]\n return Matrix([[f_x, 0, c_x],\n [ 0, f_y, c_y]]) * p_ray\n Pi = CustomFunction(\"Pi\", proj, 3, 2)\n e = x_i - Pi(dehom(exp(d) * That_cw * x_w))\n f ... | import pytest, sys
sys.path.append('..')
from sympy import symbols, eye, Matrix
from SymE3.core import Plane, LieGroup, PointH, Pixel, LieAlgebra, CustomFunction, TotalFunction, dehom, exp
def test_mirrors():
T_cw = LieGroup("{T_{cw}}")
T_ct = LieGroup("{\hat{T}_{ct}}")
p_t = PointH("{p_t}")
phat_c =... |
e = e.subs(T_ct * p_t, phat_c)
f = TotalFunction(e)
fe = f.as_explicit()
df_dd = f.diff(d, N_w)
| {
"context_start_lineno": 0,
"file": "test/mirrors.py",
"groundtruth_start_lineno": 34,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/6452"
} | {
"list": [
{
"filename": "test/bundle.py",
"retrieved_chunk": " def proj(p):\n p_ray = p / p[2, 0]\n return Matrix([[f_x, 0, c_x],\n [ 0, f_y, c_y]]) * p_ray\n Pi = CustomFunction(\"Pi\", proj, 3, 2)\n e = x_i - Pi(dehom(exp(d) * That_cw * x_w))\n f ... | inverse() * exp(d) * T_ct * p_t)) - p_c |
{
"list": [
{
"filename": "test/photo.py",
"retrieved_chunk": " phat_i = PointH(\"{\\\\hat{p}_i}\")\n def proj(p):\n p_ray = p / p[2, 0]\n f_x, f_y, c_x, c_y = symbols(\"f_x f_y c_x c_y\")\n return Matrix([[f_x, 0, c_x],\n [ 0, f_y, c_y]]) * p_ray\n... | import pytest, sys
sys.path.append('..')
from sympy import symbols, Matrix
from SymE3.core import PointH, Pixel, LieGroup, LieAlgebra, CustomFunction, TotalFunction, dehom, exp
def test_bundle_adjustment():
x_w = PointH("{x_w}")
x_i = Pixel("{x_i}")
That_cw = LieGroup("{\\hat{T}_{cw}}")
d = LieAlgebr... | {
"context_start_lineno": 0,
"file": "test/bundle.py",
"groundtruth_start_lineno": 25,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 26,
"task_id": "project_cc_python/6451"
} | {
"list": [
{
"filename": "test/photo.py",
"retrieved_chunk": " e = e.subs(That_rl * p_i, phat_i)\n f = TotalFunction(e)\n df_dd = f.diff(d)\n # Compare against ground truth\n ph = Matrix(_MatrixSym(phat_i.name, 3, 1))\n x = Matrix(_MatrixSym(x_i.name, 2, 1))\n pi = Pi.__explicit_... | diff(d, dehom(x_w), f_x, f_y, c_x, c_y) | |
{
"list": [
{
"filename": "test/bundle.py",
"retrieved_chunk": " def proj(p):\n p_ray = p / p[2, 0]\n return Matrix([[f_x, 0, c_x],\n [ 0, f_y, c_y]]) * p_ray\n Pi = CustomFunction(\"Pi\", proj, 3, 2)\n e = x_i - Pi(dehom(exp(d) * That_cw * x_w))\n f ... | import pytest, sys
sys.path.append('..')
from sympy import symbols, eye, Matrix
from SymE3.core import Plane, LieGroup, PointH, Pixel, LieAlgebra, CustomFunction, TotalFunction, dehom, exp
def test_mirrors():
T_cw = LieGroup("{T_{cw}}")
T_ct = LieGroup("{\hat{T}_{ct}}")
p_t = PointH("{p_t}")
phat_c =... | {
"context_start_lineno": 0,
"file": "test/mirrors.py",
"groundtruth_start_lineno": 39,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 40,
"task_id": "project_cc_python/6454"
} | {
"list": [
{
"filename": "test/bundle.py",
"retrieved_chunk": " def proj(p):\n p_ray = p / p[2, 0]\n return Matrix([[f_x, 0, c_x],\n [ 0, f_y, c_y]]) * p_ray\n Pi = CustomFunction(\"Pi\", proj, 3, 2)\n e = x_i - Pi(dehom(exp(d) * That_cw * x_w))\n f ... | diff(d, N_w) | |
{
"list": [
{
"filename": "sophus/se3.py",
"retrieved_chunk": " return So3.hat(omega).\\\n row_join(upsilon).\\\n col_join(sympy.Matrix.zeros(1, 4))\n @staticmethod\n def vee(Omega):\n \"\"\" R^4x4 => R^6 \"\"\"\n \"\"\" returns 6-vector representation ... | import pytest, sys
sys.path.append('..')
from sympy import Matrix, symbols, zeros, eye
from SymE3.core import Matrix3, Scalar, Point, CustomFunction, TotalFunction
from SymE3.detail import _MatrixSym
def test_embedded_deformation():
t_z = Point("{t_z}")
t_n = Point("{t_n}")
g_z = Point("{g_z}")
g_n =... |
# Compare against ground truth
rz = Matrix(_MatrixSym(R_z.name, 3, 3))
rr = Rot.__explicit__()
fe = f.as_explicit()
c = rr(rz).tomatrix()
assert c == fe.tomatrix()
assert df_dRt[:, 0] == c.diff(rz[0, 0])
assert df_dRt[:, 1] == c.diff(rz[0, 1])
assert df_dRt[:, 2] == c.diff(rz[0, 2... | {
"context_start_lineno": 0,
"file": "test/embeddef.py",
"groundtruth_start_lineno": 34,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/6455"
} | {
"list": [
{
"filename": "sophus/se3.py",
"retrieved_chunk": " upsilon_omega = \\\n Vector6(head[0], head[1], head[2], tail[0], tail[1], tail[2])\n return upsilon_omega\n def matrix(self):\n \"\"\" returns matrix representation \"\"\"\n R = self.so3.matrix()\... | diff(R_z, t_z) |
{
"list": [
{
"filename": "SymE3/numerical.py",
"retrieved_chunk": " # We have found a symbolic function, manually evaluate a placeholder continuous function\n # and set that as the value of this function at the numerical point\n if isinstance(subExpr, Float):\n return ... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
parsed.removeChildrenFrom("_PixelExpr", "Integer")
parsed.removeChildrenFrom("_PlaneExpr", "Integer")
parsed.removeChildrenFrom("_Matrix3Expr", "Integer")
parsed.removeChildrenFrom("_PointExpr", "Integer")
parsed.removeChildrenFrom("_PointHExpr", "Integer")
parsed.remove... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 47,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 48,
"task_id": "project_cc_python/6468"
} | {
"list": [
{
"filename": "SymE3/detail.py",
"retrieved_chunk": " print(\"Scalar detected in diff input, did you forget to dehom?\")\n result = super().diff(*args, **kwargs)\n if hasattr(args[0], \"rank\"):\n # Catch the edge case where matrix differentiatio... | removeChildrenFrom("Inverse", "Integer") |
{
"list": [
{
"filename": "SymE3/parse.py",
"retrieved_chunk": " else:\n self.addChild(child)\n for child in self.children:\n child.removeIdentifierPromoteChildren(id)\n def renameIdentifier(self, src, dest):\n if self.identifier == src:\n ... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
parsed.removeIdentifierPromoteChildren("Integer")
return parsed
def __explicit__(self, parsedExpression, expandLieGroupFromExp=False):
# Define wrapper functions that allow us to convert to non-expression quantities automatically
def _LieGroupExpr(name, *_):
return _Li... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 64,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 65,
"task_id": "project_cc_python/6470"
} | {
"list": [
{
"filename": "SymE3/parse.py",
"retrieved_chunk": " if self.identifier == id:\n matches.append(self)\n for child in self.children:\n matches = child.findIdentifiers(id, matches)\n return matches\n def reconstruct(self):\n result = self.... | removeIdentifierPromoteChildren("Str") |
{
"list": [
{
"filename": "sophus/se3.py",
"retrieved_chunk": " @staticmethod\n def Dxi_exp_x_matrix_at_0(i):\n v = ZeroVector6()\n v[i] = 1\n return Se3.hat(v)\n @staticmethod\n def calc_Dxi_exp_x_matrix_at_0(x, i):\n return sympy.Matrix(4, 4, lambda r, c:\n ... | import random
from sympy import MutableDenseMatrix, Symbol, Matrix, Float, eye, sin, cos
from sophus.se3 import Se3
from .detail import _Explicit, _MatrixSym
values = {}
def _resetValues():
if len(values) == 0:
random.seed(0)
def _realVal(s):
if s in values:
return values[s]
else:
... |
# Work around singularity
if perturb[3, 0] == 0 and perturb[4, 0] == 0 and perturb[5, 0] == 0:
mat = eye(4)
mat[0:3, 3] = perturb[0:3, 0]
assert v.rows == 6
assert v.shape == perturb.shape
sub = {}
for i in range(6):
sub[v[i, 0]] = perturb[i, 0]
return mat.evalf... | {
"context_start_lineno": 0,
"file": "SymE3/numerical.py",
"groundtruth_start_lineno": 98,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 99,
"task_id": "project_cc_python/6476"
} | {
"list": [
{
"filename": "sophus/se3.py",
"retrieved_chunk": " subs(x[3], 0).subs(x[4], 0).limit(x[5], 0)\nclass TestSe3(unittest.TestCase):\n def setUp(self):\n upsilon0, upsilon1, upsilon2, omega0, omega1, omega2 = sympy.symbols(\n 'upsilon[0], upsilon[1], upsilon[2]... | exp(v.as_mutable()).matrix() |
{
"list": [
{
"filename": "SymE3/detail.py",
"retrieved_chunk": " assert self.type == other.type\n if self.type == _Type.POINTH:\n explicit = result.tomatrix()\n explicit[3, 0] = 1\n result = _Explicit(explicit)\n result... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
tangent[0, col] = 0
# Substitute the perturbed matrix values in
for r in range(lieGroupMat.rows):
for c in range(lieGroupMat.cols):
explicitExpr = explicitExpr.subs(lieGroupMat[r, c], re... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 178,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 179,
"task_id": "project_cc_python/6475"
} | {
"list": [
{
"filename": "SymE3/numerical.py",
"retrieved_chunk": " else:\n for subSym in subExpr.args:\n recursiveEval(subSym)\n if isinstance(substituted, MutableDenseMatrix):\n for elem in substituted:\n recursiveEval(elem)\n else:\n ... | tomatrix(), tangent.transpose()) |
{
"list": [
{
"filename": "SymE3/parse.py",
"retrieved_chunk": "class _ParsedToken:\n def __init__(self, identifier):\n self.identifier = identifier\n self.children = []\n def hasChildren(self):\n return len(self.children) > 0\n def addChild(self, child):\n self.ch... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
parsed.renameIdentifier("_NormalExpr", "_Normal")
parsed.renameIdentifier("_PointHExpr", "_PointH")
parsed.renameIdentifier("_NormalHExpr", "_NormalH")
parsed.renameIdentifier("_PixelExpr", "_Pixel")
parsed.renameIdentifier("_PlaneExpr", "_Plane")
parsed.renameIdentifier... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 56,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 57,
"task_id": "project_cc_python/6469"
} | {
"list": [
{
"filename": "SymE3/parse.py",
"retrieved_chunk": " self.children = [child for child in self.children if child.identifier != childId]\n for child in self.children:\n child.removeChildrenFrom(parentId, childId)\n def wrapChildrenOf(self, parentId, wrapId):\n... | renameIdentifier("_PointExpr", "_Point") |
{
"list": [
{
"filename": "SymE3/detail.py",
"retrieved_chunk": " [-d[4, 0], d[3, 0], 1, d[2, 0]], \n [ 0, 0, 0, 1]])\n exp = type(f\"exp_{name}\", (Function, ), {\"__new__\": new})\n return exp;\nclass _Explicit(... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
# Remove superfluous parameters
parsed.removeChildrenFrom("Inverse", "Integer")
parsed.removeChildrenFrom("_PixelExpr", "Integer")
parsed.removeChildrenFrom("_PlaneExpr", "Integer")
parsed.removeChildrenFrom("_Matrix3Expr", "Integer")
parsed.removeChildrenFrom("... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 44,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 45,
"task_id": "project_cc_python/6467"
} | {
"list": [
{
"filename": "SymE3/numerical.py",
"retrieved_chunk": " # We have found a symbolic function, manually evaluate a placeholder continuous function\n # and set that as the value of this function at the numerical point\n if isinstance(subExpr, Float):\n return ... | wrapChildrenOf(f"self.funcs[\"{name}\"]", "*Expand") |
{
"list": [
{
"filename": "SymE3/parse.py",
"retrieved_chunk": " if self.identifier == id:\n matches.append(self)\n for child in self.children:\n matches = child.findIdentifiers(id, matches)\n return matches\n def reconstruct(self):\n result = self.... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
_resetValues()
for arg in args:
result = None
explicitExpr = self.__explicit__(parsedExpression)
if isinstance(arg, _LieAlgebraExpr):
result = explicitExpr.diff(_LieAlgebra(arg.name))
elif isinstance(arg, MatrixExpr):
r... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 119,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 120,
"task_id": "project_cc_python/6473"
} | {
"list": [
{
"filename": "sophus/complex.py",
"retrieved_chunk": " product = self.a.inv() * self.a\n self.assertEqual(product.simplify(),\n Complex.identity())\n def test_derivatives(self):\n d = sympy.Matrix(2, 2, lambda r, c: sympy.diff(\n ... | findIdentifiers("_LieAlgebraExpr", lieAlgebras) |
{
"list": [
{
"filename": "SymE3/detail.py",
"retrieved_chunk": " if hasattr(self, \"type\"):\n if self.type == _Type.POINTH and result.shape == (4, 1):\n explicit = result.tomatrix()\n explicit[3, 0] = 1\n result = _Explicit(explicit)\n ... | from functools import reduce
from typing import Tuple as tTuple
from sympy import srepr, MatrixSymbol, Symbol, MatrixExpr, Expr, Matrix, Basic, Function, preorder_traversal, eye, symbols, zeros, oo
from sympy.core.sympify import _sympify
from .detail import _Type, _PointH, _Point, _NormalH, _Normal, _Pixel, _Plane, ... |
return _Explicit([[a[0, 0]], [a[1, 0]], [a[2, 0]]])
return a
return eval(parsedExpression.reconstruct())
def as_explicit(self):
return self.__explicit__(self.__parseExpression__(True))
def diff(self, *args):
combinedResult = None
parsedExpress... | {
"context_start_lineno": 0,
"file": "SymE3/core.py",
"groundtruth_start_lineno": 103,
"repository": "mp3guy-SymE3-445731e",
"right_context_start_lineno": 104,
"task_id": "project_cc_python/6471"
} | {
"list": [
{
"filename": "sophus/matrix.py",
"retrieved_chunk": "def Vector6(a, b, c, d, e, f):\n return sympy.Matrix([a, b, c, d, e, f])\ndef ZeroVector6():\n return Vector6(0, 0, 0, 0, 0, 0)\ndef proj(v):\n m, n = v.shape\n assert m > 1\n assert n == 1\n list = [v[i] / v[m - 1] fo... | POINTH or a.type == _Type.NORMALH: |
{
"list": [
{
"filename": "py115/_internal/api/file.py",
"retrieved_chunk": " def parse_result(self, result: dict) -> str:\n err_code = api.find_error_code(result)\n if err_code != 0:\n raise api.ApiException(code=err_code)\n return result.get('video_url')",
"s... | __author__ = 'deadblue'
import time as timelib
import typing
from py115._internal.protocol import api
_app_id_mapping = {
'web': 0,
'mac': 7,
'linux': 7,
'windows': 7,
}
class _BaseApi(api.ApiSpec):
def parse_result(self, result: dict) -> typing.Any:
if result.get('state', 0) != 1:
... |
return result.get('data')
class TokenApi(_BaseApi):
def __init__(self, app_name: str) -> None:
super().__init__(
f'https://qrcodeapi.115.com/api/1.0/{app_name}/1.0/token', True
)
class StatusApi(_BaseApi):
def __init__(self, uid: str, time: int, sign: str) -> None:
... | {
"context_start_lineno": 0,
"file": "py115/_internal/api/qrcode.py",
"groundtruth_start_lineno": 20,
"repository": "deadblue-py115-ecdcb93",
"right_context_start_lineno": 21,
"task_id": "project_cc_python/6551"
} | {
"list": [
{
"filename": "py115/_internal/api/offline.py",
"retrieved_chunk": " tasks = result.get('tasks', None)\n return {\n 'page_count': result.get('page_count', 1),\n 'page': result.get('page', 1),\n 'task_count': result.get('count', 0),\n ... | ApiException(code=result.get('code')) |
{
"list": [
{
"filename": "examples/train/train_bearl.py",
"retrieved_chunk": " reward_scale=args.reward_scale,\n cost_scale=args.cost_scale)\n trainloader = DataLoader(\n dataset,\n batch_size=args.batch_size,\n pin... | import os
import uuid
import types
from dataclasses import asdict, dataclass
from typing import Any, DefaultDict, Dict, List, Optional, Tuple
import bullet_safety_gym # noqa
import dsrl
import gymnasium as gym # noqa
import numpy as np
import pyrallis
import torch
from dsrl.infos import DENSITY_CFG
from dsrl.offline... |
# setup model
model = COptiDICE(
state_dim=env.observation_space.shape[0],
action_dim=env.action_space.shape[0],
max_action=env.action_space.high[0],
f_type=args.f_type,
init_state_propotion=init_s_propotion,
observations_std=obs_std,
actions_std=act_std... | {
"context_start_lineno": 0,
"file": "examples/train/train_coptidice.py",
"groundtruth_start_lineno": 95,
"repository": "liuzuxin-OSRL-6ede2c2",
"right_context_start_lineno": 96,
"task_id": "project_cc_python/6507"
} | {
"list": [
{
"filename": "examples/train/train_bearl.py",
"retrieved_chunk": " best_reward = -np.inf\n best_cost = np.inf\n best_idx = 0\n # training\n for step in trange(args.update_steps, desc=\"Training\"):\n batch = next(trainloader_iter)\n observations, next_observat... | get_dataset_states() |
{
"list": [
{
"filename": "osrl/algorithms/bc.py",
"retrieved_chunk": " self.bc_mode = bc_mode\n self.cost_limit = cost_limit\n self.model.setup_optimizers(actor_lr)\n def set_target_cost(self, target_cost):\n self.cost_limit = target_cost\n def train_one_step(self, o... | from dataclasses import asdict, dataclass
from typing import Any, DefaultDict, Dict, List, Optional, Tuple
import dsrl
import gymnasium as gym # noqa
import numpy as np
import pyrallis
import torch
from pyrallis import field
from osrl.algorithms import BC, BCTrainer
from osrl.common.exp_util import load_config_and_m... |
ret, cost, length = trainer.evaluate(args.eval_episodes)
normalized_ret, normalized_cost = env.get_normalized_score(ret, cost)
print(
f"Eval reward: {ret}, normalized reward: {normalized_ret}; target cost {target_cost}, real cost {cost}, normalized cost: {normalized_... | {
"context_start_lineno": 0,
"file": "examples/eval/eval_bc.py",
"groundtruth_start_lineno": 60,
"repository": "liuzuxin-OSRL-6ede2c2",
"right_context_start_lineno": 61,
"task_id": "project_cc_python/6505"
} | {
"list": [
{
"filename": "examples/train/train_bc.py",
"retrieved_chunk": " TransitionDataset(data),\n batch_size=args.batch_size,\n pin_memory=True,\n num_workers=args.num_workers,\n )\n trainloader_iter = iter(trainloader)\n # for saving the best\n best_rewar... | set_target_cost(target_cost) |
{
"list": [
{
"filename": "osrl/algorithms/bcql.py",
"retrieved_chunk": " p.requires_grad = False\n for p in self.cost_critic.parameters():\n p.requires_grad = False\n for p in self.vae.parameters():\n p.requires_grad = False\n actions = self.actor... | # reference: https://github.com/aviralkumar2907/BEAR
from copy import deepcopy
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
from fsrl.utils import DummyLogger, WandbLogger
from tqdm.auto import trange # noqa
from osrl.common.net import (VAE, EnsembleDoubleQCritic, LagrangianPIDContro... |
qc_penalty = ((qc_val - self.qc_thres) * multiplier).mean()
q_val = torch.min(q_val1, q_val2)
if self.n_train_steps >= self.start_update_policy_step:
loss_actor = (-q_val + self.log_alpha.exp() *
(mmd_loss - self.target_mmd_thresh)).mean()
else:
... | {
"context_start_lineno": 0,
"file": "osrl/algorithms/bearl.py",
"groundtruth_start_lineno": 244,
"repository": "liuzuxin-OSRL-6ede2c2",
"right_context_start_lineno": 245,
"task_id": "project_cc_python/6485"
} | {
"list": [
{
"filename": "osrl/algorithms/bcql.py",
"retrieved_chunk": " with torch.no_grad():\n multiplier = self.controller.control(qc_pi).detach()\n qc_penalty = ((qc_pi - self.qc_thres) * multiplier).mean()\n loss_actor = -q_pi.mean() + qc_penalty\n self.act... | control(qc_val).detach() |
{
"list": [
{
"filename": "examples/train/train_bearl.py",
"retrieved_chunk": " best_reward = -np.inf\n best_cost = np.inf\n best_idx = 0\n # training\n for step in trange(args.update_steps, desc=\"Training\"):\n batch = next(trainloader_iter)\n observations, next_observat... | import os
import uuid
import types
from dataclasses import asdict, dataclass
from typing import Any, DefaultDict, Dict, List, Optional, Tuple
import bullet_safety_gym # noqa
import dsrl
import gymnasium as gym # noqa
import numpy as np
import pyrallis
import torch
from dsrl.infos import DENSITY_CFG
from dsrl.offline... |
# evaluation
if (step + 1) % args.eval_every == 0 or step == args.update_steps - 1:
ret, cost, length = trainer.evaluate(args.eval_episodes)
logger.store(tab="eval", Cost=cost, Reward=ret, Length=length)
# save the current weight
logger.save_checkpoint(... | {
"context_start_lineno": 0,
"file": "examples/train/train_bc.py",
"groundtruth_start_lineno": 119,
"repository": "liuzuxin-OSRL-6ede2c2",
"right_context_start_lineno": 120,
"task_id": "project_cc_python/6514"
} | {
"list": [
{
"filename": "examples/train/train_cpq.py",
"retrieved_chunk": " observations, next_observations, actions, rewards, costs, done = [\n b.to(args.device) for b in batch\n ]\n trainer.train_one_step(observations, next_observations, actions, rewards, costs,\n ... | train_one_step(observations, actions) |
{
"list": [
{
"filename": "tests/test_base.py",
"retrieved_chunk": " \"logcosh\": None,\n },\n }\n def setUp(self) -> None:\n self.X, self.y = load_diabetes(return_X_y=True)\n self.seed = 0\n self.X_train, self.X_test, self.y_train, self.y_test = train_test... | from unittest import TestCase
from catboost import CatBoostClassifier, CatboostError, CatBoostRegressor
from parameterized import parameterized
from sklearn.datasets import load_diabetes, load_digits
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from boost_loss.sklearn imp... |
self.assertEqual(y_test.shape, y_pred.shape)
self.assertEqual(y_test.shape, y_pred_var.shape)
self.assertFalse(hasattr(CatBoostRegressor(), "predict_var"))
# assert method properly created for each object
with self.assertRaises(CatboostError):
patch_catboost(
... | {
"context_start_lineno": 0,
"file": "tests/test_sklearn.py",
"groundtruth_start_lineno": 21,
"repository": "34j-boost-loss-ff08630",
"right_context_start_lineno": 22,
"task_id": "project_cc_python/6630"
} | {
"list": [
{
"filename": "tests/test_base.py",
"retrieved_chunk": " self.X_train = x_scaler.fit_transform(self.X_train)\n self.X_test = x_scaler.transform(self.X_test)\n self.y_train = y_scaler.fit_transform(self.y_train.reshape(-1, 1)).ravel()\n self.y_test = y_scaler.tra... | predict_var(X_test) |
{
"list": [
{
"filename": "osrl/algorithms/cpq.py",
"retrieved_chunk": " for p in self.critic.parameters():\n p.requires_grad = False\n for p in self.cost_critic.parameters():\n p.requires_grad = False\n actions, _ = self._actor_forward(observations, False, T... | # reference: https://github.com/sfujim/BCQ
from copy import deepcopy
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
from fsrl.utils import DummyLogger, WandbLogger
from tqdm.auto import trange # noqa
from osrl.common.net import (VAE, EnsembleDoubleQCritic, LagrangianPIDController,
... |
qc_penalty = ((qc_pi - self.qc_thres) * multiplier).mean()
loss_actor = -q_pi.mean() + qc_penalty
self.actor_optim.zero_grad()
loss_actor.backward()
self.actor_optim.step()
stats_actor = {
"loss/actor_loss": loss_actor.item(),
"loss/qc_penalty":... | {
"context_start_lineno": 0,
"file": "osrl/algorithms/bcql.py",
"groundtruth_start_lineno": 195,
"repository": "liuzuxin-OSRL-6ede2c2",
"right_context_start_lineno": 196,
"task_id": "project_cc_python/6481"
} | {
"list": [
{
"filename": "osrl/algorithms/cpq.py",
"retrieved_chunk": " self.actor_optim.step()\n stats_actor = {\"loss/actor_loss\": loss_actor.item()}\n for p in self.critic.parameters():\n p.requires_grad = True\n for p in self.cost_critic.parameters():\n ... | control(qc_pi).detach() |
{
"list": [
{
"filename": "examples/train/train_bearl.py",
"retrieved_chunk": " best_reward = -np.inf\n best_cost = np.inf\n best_idx = 0\n # training\n for step in trange(args.update_steps, desc=\"Training\"):\n batch = next(trainloader_iter)\n observations, next_observat... | import os
import uuid
import types
from dataclasses import asdict, dataclass
from typing import Any, DefaultDict, Dict, List, Optional, Tuple
import bullet_safety_gym # noqa
import dsrl
import gymnasium as gym # noqa
import numpy as np
import pyrallis
import torch
from dsrl.infos import DENSITY_CFG
from dsrl.offline... |
# evaluation
if (step + 1) % args.eval_every == 0 or step == args.update_steps - 1:
ret, cost, length = trainer.evaluate(args.eval_episodes)
logger.store(tab="eval", Cost=cost, Reward=ret, Length=length)
# save the current weight
logger.save_checkpoint(... | {
"context_start_lineno": 0,
"file": "examples/train/train_coptidice.py",
"groundtruth_start_lineno": 143,
"repository": "liuzuxin-OSRL-6ede2c2",
"right_context_start_lineno": 144,
"task_id": "project_cc_python/6510"
} | {
"list": [
{
"filename": "examples/train/train_bearl.py",
"retrieved_chunk": " done)\n # evaluation\n if (step + 1) % args.eval_every == 0 or step == args.update_steps - 1:\n ret, cost, length = trainer.evaluate(args.eval_episodes)\n l... | train_one_step(batch) |
{
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " pytest.param(0.3, np.linspace(0, 1000, 11), id='0.3'),\n pytest.param(0.4, np.linspace(0, 1000, 11), id='0.4'),\n pytest.param(0.5, np.linspace(0, 1000, 11), id='0.5'),\n pytest.param(0.8, np.linsp... | import numpy as np
import numpy.testing as npt
import pytest
import torch
from utils.data_simulation.GenerateData import GenerateData
from src.original.ETP_SRI.LinearFitting import LinearFit
#run using python -m pytest from the root folder
test_linear_data = [
pytest.param(0, np.linspace(0, 1000, 11), id='0'),
... |
npt.assert_allclose([f, D], [f_fit, D_fit], atol=1e-5)
if not np.allclose(f, 0):
npt.assert_allclose(Dp, Dp_fit, rtol=1e-2, atol=1e-3)
| {
"context_start_lineno": 0,
"file": "tests/IVIMmodels/unit_tests/test_ivim_fit_linear.py",
"groundtruth_start_lineno": 43,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 44,
"task_id": "project_cc_python/6529"
} | {
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " testing_signal = np.exp(-D * np.asarray(bvals, dtype='float64'))\n npt.assert_allclose(gd_signal, testing_signal)\n assert(gd_signal[0] >= testing_signal[0])\ntest_ivim_data = [\n pytest.param(0.01... | ivim_fit(bvals, gd_signal) |
{
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " pytest.param(0.3, np.linspace(0, 1000, 11), id='0.3'),\n pytest.param(0.4, np.linspace(0, 1000, 11), id='0.4'),\n pytest.param(0.5, np.linspace(0, 1000, 11), id='0.5'),\n pytest.param(0.8, np.linsp... | import numpy as np
import numpy.testing as npt
import pytest
import torch
from utils.data_simulation.GenerateData import GenerateData
from src.original.ETP_SRI.LinearFitting import LinearFit
#run using python -m pytest from the root folder
test_linear_data = [
pytest.param(0, np.linspace(0, 1000, 11), id='0'),
... |
fit = LinearFit()
[f_fit, D_fit, Dp_fit] = fit.ivim_fit(bvals, gd_signal)
npt.assert_allclose([f, D], [f_fit, D_fit], atol=1e-5)
if not np.allclose(f, 0):
npt.assert_allclose(Dp, Dp_fit, rtol=1e-2, atol=1e-3)
| {
"context_start_lineno": 0,
"file": "tests/IVIMmodels/unit_tests/test_ivim_fit_linear.py",
"groundtruth_start_lineno": 41,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 42,
"task_id": "project_cc_python/6528"
} | {
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " testing_signal = np.exp(-D * np.asarray(bvals, dtype='float64'))\n npt.assert_allclose(gd_signal, testing_signal)\n assert(gd_signal[0] >= testing_signal[0])\ntest_ivim_data = [\n pytest.param(0.01... | ivim_signal(D, Dp, f, 1, bvals) |
{
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_sivim.py",
"retrieved_chunk": " self.bounds = np.array([(0, 0, 0), (np.inf, 1, 0.004)])\n else:\n self.bounds = np.array([(0, *bounds[0]), (np.inf, *bounds[1])])\n def set_initial_guess(self, ini... | import numpy as np
from dipy.core.gradients import gradient_table
from scipy.stats import norm
import matplotlib.pyplot as plt
import scienceplots
import ivim_fit_method_biexp
import ivim_fit_method_subtracted
import ivim_fit_method_sivim
import ivim_fit_method_linear
import ivim_fit_method_segmented_3step
import ivim_... |
linear_fit = linear_model.fit(noised_signal)
# Subtracted fit (Le Bihan 2019)
subtracted_model = ivim_fit_method_subtracted.IvimModelSubtracted(gtab, bounds=bounds_mm, initial_guess=initial_guess_mm, rescale_units=rescale_units)#, b_threshold_lower=0.2, b_threshold_upper=0.1)
subtracted_fit = subtracted_model.fit(noi... | {
"context_start_lineno": 0,
"file": "src/original/IAR_LundUniversity/simple_test_of_fits.py",
"groundtruth_start_lineno": 93,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 94,
"task_id": "project_cc_python/6518"
} | {
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_sivim.py",
"retrieved_chunk": " # Rescale the guess\n self.initial_guess = (self.initial_guess[0], self.initial_guess[1], \\\n self.initial_guess[2]*1000)\n # Rescale the bounds\n... | IvimModelLinear(gtab, b_threshold=0.2, bounds=bounds_mm_sivim, rescale_units=rescale_units) |
{
"list": [
{
"filename": "utils/data_simulation/GenerateData.py",
"retrieved_chunk": " assert len(D) == len(F), 'D and F must be the same length'\n signal = self._op.zeros_like(bvalues)\n for [d, f] in zip(D, F):\n signal += f * self.linear_signal(d, bvalues)\n ... | import numpy as np
import numpy.polynomial.polynomial as poly
from utils.data_simulation.GenerateData import GenerateData
class LinearFit:
"""
Performs linear fits of exponential data
"""
def __init__(self, linear_cutoff=500):
"""
Parameters
----------
linear_cutoff :... |
Dp_prime = self.linear_fit(bvalues[lt_cutoff], np.log(signal_Dp))
if np.any(np.asarray(Dp_prime) < 0) or not np.all(np.isfinite(Dp_prime)):
print('Perfusion fit failed')
Dp_prime = [0, 0]
f = signal[0] - D[0]
else:
... | {
"context_start_lineno": 0,
"file": "src/original/ETP_SRI/LinearFitting.py",
"groundtruth_start_lineno": 67,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 68,
"task_id": "project_cc_python/6524"
} | {
"list": [
{
"filename": "utils/data_simulation/GenerateData.py",
"retrieved_chunk": " assert len(D) == len(F), 'D and F must be the same length'\n signal = self._op.zeros_like(bvalues)\n for [d, f] in zip(D, F):\n signal += f * self.linear_signal(d, bvalues)\n ... | linear_signal(D[1], bvalues[lt_cutoff], np.log(D[0])) |
{
"list": [
{
"filename": "tests/IVIMmodels/unit_tests/test_ivim_fit_linear.py",
"retrieved_chunk": " pytest.param(0.4, 0.001, 0.05, np.linspace(0, 1000, 11), id='0.4'),\n pytest.param(0.5, 0.001, 0.05, np.linspace(0, 1000, 11), id='0.5'),\n]\n@pytest.mark.parametrize(\"f, D, Dp, bvals\", test_i... | import numpy as np
import numpy.testing as npt
import pytest
import torch
from utils.data_simulation.GenerateData import GenerateData
#run using python -m pytest from the root folder
test_monoexponential_data = [
pytest.param(0, np.linspace(0, 1000, 11), id='0'),
pytest.param(0.1, np.linspace(0, 1000, 11), i... |
testing_signal = S0 * ((1 - f) * np.exp(-D * bvals) + f * np.exp(-Dp * bvals))
atol = 0.0
if snr is not None:
atol = 4 / snr
npt.assert_allclose(gd_signal, testing_signal, atol=atol)
test_linear_data = [
pytest.param(0, np.linspace(0, 1000, 11), 0, id='0'),
pytest.param(0.1, np.linspa... | {
"context_start_lineno": 0,
"file": "tests/IVIMmodels/data/test_GenerateData.py",
"groundtruth_start_lineno": 39,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 40,
"task_id": "project_cc_python/6531"
} | {
"list": [
{
"filename": "tests/IVIMmodels/unit_tests/test_ivim_fit_linear.py",
"retrieved_chunk": " gd_signal = gd.exponential_signal(D, bvals)\n print(gd_signal)\n fit = LinearFit()\n D_fit = fit.linear_fit(bvals, np.log(gd_signal))\n npt.assert_allclose([1, D], D_fit)\ntest_ivim_dat... | ivim_signal(D, Dp, f, S0, bvals, snr) |
{
"list": [
{
"filename": "src/original/DK_OGC_AmsterdamUMC/utils/data_processing/processors/AverageSignalsOfEqualXvals.py",
"retrieved_chunk": " subject.add_image(torchio.Image(tensor=torch.Tensor(signals)), 'signals')\n subject.add_image(torchio.Image(tensor=torch.Tensor(np.reshape(xva... | import torch
import numpy as np
from utils.ivim.forward_model import ivim_parameters_to_signal
def simulate_ivim_signal(D, Dp, f, S0, bvalues, SNR_array, rg):
"""
simulate ivim signal
Args:
D: diffusion coefficient
Dp: pseudo diffusion coefficient
f: perfusion fraction
S0... |
# create 2 signal arrays filled with gaussian noise
noise_real = rg.normal(0, 1 / SNR, (1, len(bvalues)))
noise_imag = rg.normal(0, 1 / SNR, (1, len(bvalues)))
# add Rician noise to the simulated data
simulated_data = np.sqrt(np.power(simulated_data + noise_real, 2) + np.power(noise_imag, 2)).squ... | {
"context_start_lineno": 0,
"file": "utils/data_simulation/ivim_simulation.py",
"groundtruth_start_lineno": 27,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/6525"
} | {
"list": [
{
"filename": "src/original/DK_OGC_AmsterdamUMC/utils/data_processing/processors/SortSignalOnXval.py",
"retrieved_chunk": " sorted_signals: sorted signals\n sorted_bvals: sorted bvals\n \"\"\"\n sorted_xval_idcs = np.argsort(xvals)\n sorted_xvals ... | cpu().detach().numpy() |
{
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_biexp.py",
"retrieved_chunk": " else:\n self.bounds = np.array([(0, *bounds[0]), (np.inf, *bounds[1])])\n def set_initial_guess(self, initial_guess):\n if initial_guess == None:\n self.ini... | import numpy as np
from dipy.core.gradients import gradient_table
from scipy.stats import norm
import matplotlib.pyplot as plt
import scienceplots
import ivim_fit_method_biexp
import ivim_fit_method_subtracted
import ivim_fit_method_sivim
import ivim_fit_method_linear
import ivim_fit_method_segmented_3step
import ivim_... |
subtracted_fit = subtracted_model.fit(noised_signal)
# Segmented fit (3 step) (DIPY)
segmented_3step_model = ivim_fit_method_segmented_3step.IvimModelSegmented3Step(gtab, bounds=bounds_mm, initial_guess=initial_guess_mm, rescale_units=rescale_units)#, b_threshold_lower=0.2, b_threshold_upper=0.1)
segmented_3step_fit ... | {
"context_start_lineno": 0,
"file": "src/original/IAR_LundUniversity/simple_test_of_fits.py",
"groundtruth_start_lineno": 97,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 98,
"task_id": "project_cc_python/6519"
} | {
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_biexp.py",
"retrieved_chunk": " self.initial_guess = (self.initial_guess[0], self.initial_guess[1], \\\n self.initial_guess[2]*1000, self.initial_guess[3]*1000)\n # Rescale the bounds\n ... | IvimModelSubtracted(gtab, bounds=bounds_mm, initial_guess=initial_guess_mm, rescale_units=rescale_units)#, b_threshold_lower=0.2, b_threshold_upper=0.1) |
{
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_sivim.py",
"retrieved_chunk": " self.bounds = np.array([(0, 0, 0), (np.inf, 1, 0.004)])\n else:\n self.bounds = np.array([(0, *bounds[0]), (np.inf, *bounds[1])])\n def set_initial_guess(self, ini... | import numpy as np
from dipy.core.gradients import gradient_table
from scipy.stats import norm
import matplotlib.pyplot as plt
import scienceplots
import ivim_fit_method_biexp
import ivim_fit_method_subtracted
import ivim_fit_method_sivim
import ivim_fit_method_linear
import ivim_fit_method_segmented_3step
import ivim_... |
sivim_fit = sivim_model.fit(noised_signal)
# linear fit
linear_model = ivim_fit_method_linear.IvimModelLinear(gtab, b_threshold=0.2, bounds=bounds_mm_sivim, rescale_units=rescale_units)
linear_fit = linear_model.fit(noised_signal)
# Subtracted fit (Le Bihan 2019)
subtracted_model = ivim_fit_method_subtracted.IvimMod... | {
"context_start_lineno": 0,
"file": "src/original/IAR_LundUniversity/simple_test_of_fits.py",
"groundtruth_start_lineno": 89,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 90,
"task_id": "project_cc_python/6517"
} | {
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_sivim.py",
"retrieved_chunk": " # Rescale the guess\n self.initial_guess = (self.initial_guess[0], self.initial_guess[1], \\\n self.initial_guess[2]*1000)\n # Rescale the bounds\n... | IvimModelsIVIM(gtab, b_threshold=0.2, bounds=bounds_mm_sivim, initial_guess=initial_guess_mm_sivim, rescale_units=rescale_units) |
{
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " pytest.param(0.3, np.linspace(0, 1000, 11), id='0.3'),\n pytest.param(0.4, np.linspace(0, 1000, 11), id='0.4'),\n pytest.param(0.5, np.linspace(0, 1000, 11), id='0.5'),\n pytest.param(0.8, np.linsp... | import numpy as np
import numpy.testing as npt
import pytest
import torch
from utils.data_simulation.GenerateData import GenerateData
from src.original.ETP_SRI.LinearFitting import LinearFit
#run using python -m pytest from the root folder
test_linear_data = [
pytest.param(0, np.linspace(0, 1000, 11), id='0'),
... |
npt.assert_allclose([1, D], D_fit)
test_ivim_data = [
pytest.param(0, 0.01, 0.05, np.linspace(0, 1000, 11), id='0'),
pytest.param(0.1, 0.01, 0.05, np.linspace(0, 1000, 11), id='0.1'),
pytest.param(0.2, 0.01, 0.05, np.linspace(0, 1000, 11), id='0.2'),
pytest.param(0.1, 0.05, 0.1, np.linspace(0, 100... | {
"context_start_lineno": 0,
"file": "tests/IVIMmodels/unit_tests/test_ivim_fit_linear.py",
"groundtruth_start_lineno": 27,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/6527"
} | {
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " testing_signal = np.exp(-D * np.asarray(bvals, dtype='float64'))\n npt.assert_allclose(gd_signal, testing_signal)\n assert(gd_signal[0] >= testing_signal[0])\ntest_ivim_data = [\n pytest.param(0.01... | linear_fit(bvals, np.log(gd_signal)) |
{
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_segmented_3step.py",
"retrieved_chunk": "\"\"\" Classes and functions for fitting ivim model \"\"\"\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom dipy.reconst.base import ReconstModel\nfrom dipy.reconst.multi_... | import numpy as np
from dipy.core.gradients import gradient_table
from scipy.stats import norm
import matplotlib.pyplot as plt
import scienceplots
import ivim_fit_method_biexp
import ivim_fit_method_subtracted
import ivim_fit_method_sivim
import ivim_fit_method_linear
import ivim_fit_method_segmented_3step
import ivim_... |
mix_fit = mix_model.fit(noised_signal)
mix_fit6 = mix_model.fit(noised_signal6)
# TopoPro (Fadnavis et al.)
topopro_model = ivim_fit_method_modified_topopro.IvimModelTopoPro(gtab, bounds=bounds_mm, rescale_units=rescale_units, rescale_results_to_mm2_s=True)
topopro_fit = topopro_model.fit(noised_signal)
topopro_fit6 ... | {
"context_start_lineno": 0,
"file": "src/original/IAR_LundUniversity/simple_test_of_fits.py",
"groundtruth_start_lineno": 110,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 111,
"task_id": "project_cc_python/6522"
} | {
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_segmented_3step.py",
"retrieved_chunk": " https://dipy.org/documentation/1.0.0./examples_built/reconst_ivim/\n Args:\n gtab (DIPY gradient table):\n Object that holds the diffusion encodi... | IvimModelVP(gtab, bounds=bounds_mm, rescale_units=rescale_units, rescale_results_to_mm2_s=True) |
{
"list": [
{
"filename": "nail/core/prompt/context_compiler.py",
"retrieved_chunk": " Compiles prompt context from given context_file_paths. Includes all\n files in the given paths, minus any that are included in the\n ContextCompiler's ignore_list. Context includes a prefix expl... | from nail.core.file_editor import FileEditor
from nail.core.chat import Chat
from nail.core.prompt.prompt import BuildReadmePrompt
def build_readme(readme_file_path, model=None):
"""
Gathers context from all files in the current directory, builds a prompt for
OpenAI to generate a README file for the appli... | {
"context_start_lineno": 0,
"file": "nail/tools/build_readme.py",
"groundtruth_start_lineno": 15,
"repository": "edsaav-nail-64acdc6",
"right_context_start_lineno": 16,
"task_id": "project_cc_python/6588"
} | {
"list": [
{
"filename": "nail/core/prompt/prompt.py",
"retrieved_chunk": " self.details = details\n @property\n def _context_text(self):\n if not self.context_file_paths:\n return \"\"\n return ContextCompiler(self.context_file_paths).compile_all()\n @propert... | apply_changes(readme_contents) | |
{
"list": [
{
"filename": "src/original/IAR_LundUniversity/ivim_fit_method_segmented_3step.py",
"retrieved_chunk": " \"\"\"\n self.bvals = gtab.bvals\n self.perf_b_threshold_upper = b_threshold_upper\n self.diff_b_threshold_lower = b_threshold_lower\n self.set_bounds... | import numpy as np
from dipy.core.gradients import gradient_table
from scipy.stats import norm
import matplotlib.pyplot as plt
import scienceplots
import ivim_fit_method_biexp
import ivim_fit_method_subtracted
import ivim_fit_method_sivim
import ivim_fit_method_linear
import ivim_fit_method_segmented_3step
import ivim_... |
biexp_fit = biexp_model.fit(noised_signal)
# sIVIM fit
lower_bounds_sivim = (0, 0)
upper_bounds_sivim = (1, 4/factor)
bounds_mm_sivim = (lower_bounds_sivim, upper_bounds_sivim)
initial_guess_mm_sivim = (1, 0.2, 0.001)
sivim_model = ivim_fit_method_sivim.IvimModelsIVIM(gtab, b_threshold=0.2, bounds=bounds_mm_sivim, in... | {
"context_start_lineno": 0,
"file": "src/original/IAR_LundUniversity/simple_test_of_fits.py",
"groundtruth_start_lineno": 81,
"repository": "OSIPI-TF2.4_IVIM-MRI_CodeCollection-686d23e",
"right_context_start_lineno": 82,
"task_id": "project_cc_python/6516"
} | {
"list": [
{
"filename": "tests/IVIMmodels/data/test_GenerateData.py",
"retrieved_chunk": " npt.assert_allclose(gd_signal, testing_signal, atol=atol)\ntest_linear_data = [\n pytest.param(0, np.linspace(0, 1000, 11), 0, id='0'),\n pytest.param(0.1, np.linspace(0, 1000, 11), 10, id='0.1'),\n ... | IvimModelBiExp(gtab, bounds=bounds_mm, initial_guess=initial_guess_mm, rescale_units=rescale_units) |
{
"list": [
{
"filename": "tests/core/prompt/test_formatting_utils.py",
"retrieved_chunk": "from pathlib import Path\nfrom nail.core.prompt.formatting_utils import file_block\ndef test_file_block(tmp_path: Path):\n # Create a temporary file with content\n file_path = tmp_path / \"test_file.txt\"... | import pytest
from unittest.mock import patch
from nail.core.file_editor import FileEditor, MissingFilePathError
def test_missing_file_path_error():
with pytest.raises(MissingFilePathError):
FileEditor()
def test_exists(tmp_path):
file_path = tmp_path / "test.txt"
file_path.write_text("Test con... |
assert file_editor.content() == "New content"
# Mock input to return 'n' for discard changes
monkeypatch.setattr("builtins.input", lambda _: "n")
assert file_editor.apply_changes("Another content") is False
assert file_editor.content() == "New content"
# Check if the diff is printed correctl... | {
"context_start_lineno": 0,
"file": "tests/core/test_file_editor.py",
"groundtruth_start_lineno": 52,
"repository": "edsaav-nail-64acdc6",
"right_context_start_lineno": 53,
"task_id": "project_cc_python/6607"
} | {
"list": [
{
"filename": "tests/core/prompt/test_formatting_utils.py",
"retrieved_chunk": "from pathlib import Path\nfrom nail.core.prompt.formatting_utils import file_block\ndef test_file_block(tmp_path: Path):\n # Create a temporary file with content\n file_path = tmp_path / \"test_file.txt\"... | apply_changes("New content") is True |
{
"list": [
{
"filename": "tests/test_main.py",
"retrieved_chunk": " assert result.exit_code == 0\n mock_debug_file.assert_called_once_with(\"test_file\", None, None)\ndef test_spec(runner):\n with patch(\"nail.main.build_spec_file\") as mock_build_spec_file:\n result = runner.... | import pytest
import tempfile
from pathlib import Path
from nail.core.prompt.context_compiler import ContextCompiler
@pytest.fixture
def temp_files():
with tempfile.TemporaryDirectory() as temp_dir:
temp_dir_path = Path(temp_dir)
file_names = ["file1.txt", "file2.py", "_hidden.txt", "test_file.py... |
assert "file1.txt" in result
assert "file2.py" in result
assert "_hidden.txt" in result
assert "test_file.py" in result
def test_compile_all_minus_ignored(temp_files):
context_compiler = ContextCompiler(context_file_paths=[temp_files])
result = context_compiler.compile_all_minus_ignored()
... | {
"context_start_lineno": 0,
"file": "tests/core/prompt/test_context_compiler.py",
"groundtruth_start_lineno": 21,
"repository": "edsaav-nail-64acdc6",
"right_context_start_lineno": 22,
"task_id": "project_cc_python/6613"
} | {
"list": [
{
"filename": "tests/core/prompt/test_formatting_utils.py",
"retrieved_chunk": "from pathlib import Path\nfrom nail.core.prompt.formatting_utils import file_block\ndef test_file_block(tmp_path: Path):\n # Create a temporary file with content\n file_path = tmp_path / \"test_file.txt\"... | CONTEXT_PREFIX in result |
{
"list": [
{
"filename": "nail/core/chat.py",
"retrieved_chunk": " try:\n self.model = SUPPORTED_MODELS[self.model_name]()\n except KeyError:\n raise InvalidModelError(f\"Unsupported model: {self.model_name}\")\n @property\n def _default_model(self):\n ... | from abc import ABC, abstractmethod
from nail.core.file_editor import FileEditor
from nail.core.prompt.context_compiler import ContextCompiler
from nail.core.prompt.formatting_utils import file_block
from nail.core.config.local_config_utils import load_local_config
BUILD_REQUEST = "Write code to the following specifi... |
return "" if not instruction else f"\n{instruction}"
@abstractmethod
def text(self):
pass
class BuildPrompt(BasePrompt):
def text(self):
return (
self._context_text
+ f"{BUILD_REQUEST}\n"
+ self._file_text
+ self._custom_instruction... | {
"context_start_lineno": 0,
"file": "nail/core/prompt/prompt.py",
"groundtruth_start_lineno": 49,
"repository": "edsaav-nail-64acdc6",
"right_context_start_lineno": 50,
"task_id": "project_cc_python/6602"
} | {
"list": [
{
"filename": "nail/core/chat.py",
"retrieved_chunk": " try:\n self.model = SUPPORTED_MODELS[self.model_name]()\n except KeyError:\n raise InvalidModelError(f\"Unsupported model: {self.model_name}\")\n @property\n def _default_model(self):\n ... | get("prompt_instructions", {}).get(key) |
{
"list": [
{
"filename": "Alphassembly/assembler/glang/glc.py",
"retrieved_chunk": " cmd(f\"..\\\\main.py {filename} {output}\", f\"alsm {filename} {output}\")\ndef cmd(command, message=None):\n if not silent:\n if message is None:\n clog.log(f\"[CMD] {command}\")\n els... | from concurrent.futures import process
import os
import clog
import subprocess as sp
import sys
def test(filename):
split_text = os.path.splitext(filename)
extless = split_text[0]
if split_text[-1] == ".as":
stdout = []
stderr = []
clog.log(f"Compiling to tests/{extless}.asb")
... |
return ret
return 0
errors = 0
for file in os.listdir("tests"):
if test(file) != 0:
errors += 1
msg = " errors" if errors >= 2 or errors == 0 else " error"
print(f"\nTesting ended with {errors}" + msg)
if errors != 0:
print("See text files in the tests directory to see what ... | {
"context_start_lineno": 0,
"file": "Alphassembly/assembler/run_tests.py",
"groundtruth_start_lineno": 44,
"repository": "AlphaDinosaur89-glang-de75a3e",
"right_context_start_lineno": 45,
"task_id": "project_cc_python/6655"
} | {
"list": [
{
"filename": "Alphassembly/assembler/glang/glc.py",
"retrieved_chunk": " included_files = []\n while i < len(tokens):\n token = tokens[i]\n if token.matches(TT_KEYWORD, 'include'):\n token = tokens[i+1]\n if token.type != TT_STRING:\n ... | error(f"Test of {filename} failed with exit code: {ret}") |
{
"list": [
{
"filename": "docile/evaluation/pcc_field_matching.py",
"retrieved_chunk": " Parameters\n ----------\n predictions\n Either KILE fields from one page/document or LI fields from one line item. Notice\n that one line item can span multiple pages. These predictions are... | from collections import defaultdict
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
import networkx
from docile.dataset import BBox, Field
from docile.evaluation.pcc import PCCSet
from docile.evaluation.pcc_field_matching import FieldMatching, get_matches
class LineItemsGraph:
"""
Class r... |
pred_line_items = defaultdict(list)
pred_i_to_index_in_li = {}
for pred_i, pred in enumerate(predictions):
li_i = _get_line_item_id(pred)
pred_i_to_index_in_li[pred_i] = len(pred_line_items[li_i])
pred_line_items[li_i].append(pred)
gold_line_items = defaultdict(list)
for g... | {
"context_start_lineno": 0,
"file": "docile/evaluation/line_item_matching.py",
"groundtruth_start_lineno": 107,
"repository": "congtuong-docile-44e4fce",
"right_context_start_lineno": 108,
"task_id": "project_cc_python/6617"
} | {
"list": [
{
"filename": "docile/evaluation/pcc_field_matching.py",
"retrieved_chunk": " Pseudo-Character-Centers (PCCs) covering all pages that have any of the\n predictions/annotations fields.\n iou_threshold\n Necessary 'intersection / union' to accept a pair of fields as a... | empty(predictions, annotations), {}) |
{
"list": [
{
"filename": "subchain/client.py",
"retrieved_chunk": " sys.exit(1)\n print(s.recv(1024).decode())\n data = 'uploadTx'.encode()\n s.send(data)\n response = s.recv(BUFFER_SIZE)\n data = json.dumps(tx_info).encode()\n s.send(data)\n s.close()\ndef rev_file(conn, ... | import socket
import threading
import sys
import struct
import os
import json
import pathlib
from dag_model.dag import DAG
import dag_model.transaction as transaction
BUFFER_SIZE = 1024
def create_server_socket(dag_obj, num_shards = 5):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s... |
transaction.tx_save(new_tx)
dag_obj.tx_publish(new_tx)
print(f"The new block {new_tx.tx_name} has been published!")
conn.close() | {
"context_start_lineno": 0,
"file": "mainchain/dag_socket/server.py",
"groundtruth_start_lineno": 60,
"repository": "david-stan-dagfed-chain-0a60a23",
"right_context_start_lineno": 61,
"task_id": "project_cc_python/6682"
} | {
"list": [
{
"filename": "subchain/client.py",
"retrieved_chunk": " header = conn.recv(header_size)\n _, tx_size = struct.unpack('64si', header)\n print(f\"Size of the block is {tx_size}\")\n conn.send('header_resp'.encode())\n with open(tx_file_path, 'wb') as f:\n bytes_receive... | MainchainTransaction(**json_tx_data) |
{
"list": [
{
"filename": "docile/evaluation/evaluate.py",
"retrieved_chunk": " \"layout clusters with `x` documents for training available. Here 'training' means \"\n \"trainval for test and train for val.\"\n )\n legend.append(\n \"*... | import json
from typing import Any, Dict, List, Optional, Tuple
from docile.dataset.cached_object import CachedObject, CachingConfig
from docile.dataset.field import Field
from docile.dataset.paths import PathMaybeInZip
from docile.dataset.table_grid import TableGrid
class DocumentAnnotation(CachedObject[Dict]):
... |
super().__init__(path=path, cache=cache)
def from_disk(self) -> Dict[str, Any]:
return json.loads(self.path.read_bytes())
@property
def page_count(self) -> int:
return self.content["metadata"]["page_count"]
@property
def fields(self) -> List[Field]:
"""All KILE fi... | {
"context_start_lineno": 0,
"file": "docile/dataset/document_annotation.py",
"groundtruth_start_lineno": 27,
"repository": "congtuong-docile-44e4fce",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/6618"
} | {
"list": [
{
"filename": "docile/evaluation/evaluate.py",
"retrieved_chunk": " )\n if include_same_text:\n legend.append(\n \"* '{TASK} (with text comparison)' means that matches found based on location are \"\n \"considered as a false positive a... | DISK) -> None: |
{
"list": [
{
"filename": "mainchain/dag_model/transaction.py",
"retrieved_chunk": "timestamp - timestamp of the block\nmodel_accuracy - accuracy of the aggregated model\nparam_hash - hash of the parameters file\n\"\"\"\nclass MainchainTransaction:\n def __init__(self,\n ... | import os
import shutil
import sys
import pathlib
import torch
import time
import uuid
import json
import random
import copy
import subprocess
import threading
import client
import fabric_api
sys.path.append('./ml')
sys.path.append('../')
# sys.path.append('../../commonComponent')
from ml.utils.settings import BaseS... |
time.sleep(1)
iteration = 0
while 1:
print(f"********************* Iteration {iteration} ***************************")
taskID = str(uuid.uuid4())[:8]
apv_tx_cands = []
client.require_tips_from_server("localhost")
# implement promise later
time.sleep(2)
... | {
"context_start_lineno": 0,
"file": "subchain/shard_run.py",
"groundtruth_start_lineno": 87,
"repository": "david-stan-dagfed-chain-0a60a23",
"right_context_start_lineno": 88,
"task_id": "project_cc_python/6684"
} | {
"list": [
{
"filename": "mainchain/dag_model/transaction.py",
"retrieved_chunk": " model_accuracy = 0.0,\n ) -> None:\n self.param_hash = param_hash\n self.timestamp = timestamp\n self.shard_id = shard_id\n self.approved_tips = approved_tips... | upload_tx_to_server("localhost", genesisTxInfo) |
{
"list": [
{
"filename": "docile/dataset/document_ocr.py",
"retrieved_chunk": " self.pdf_path = pdf_path\n def from_disk(self) -> Dict:\n return json.loads(self.path.read_bytes())\n def to_disk(self, content: Any) -> None:\n self.path.full_path.parent.mkdir(parents=True, ex... | import json
from typing import Any, Dict, List, Optional, Tuple
from docile.dataset.cached_object import CachedObject, CachingConfig
from docile.dataset.field import Field
from docile.dataset.paths import PathMaybeInZip
from docile.dataset.table_grid import TableGrid
class DocumentAnnotation(CachedObject[Dict]):
... |
def page_fields(self, page: int) -> List[Field]:
"""KILE fields on the given page of the document."""
return [f for f in self.fields if f.page == page]
@property
def li_fields(self) -> List[Field]:
"""All LI fields on the document."""
return [Field.from_dict(a) for a in se... | {
"context_start_lineno": 0,
"file": "docile/dataset/document_annotation.py",
"groundtruth_start_lineno": 40,
"repository": "congtuong-docile-44e4fce",
"right_context_start_lineno": 41,
"task_id": "project_cc_python/6619"
} | {
"list": [
{
"filename": "docile/dataset/document_images.py",
"retrieved_chunk": " page_path = DataPaths.cache_page_image_path(self.path, page_i)\n with Image.open(str(page_path)) as page_img:\n try:\n page_img.load()\n except Exc... | from_dict(a) for a in self.content["field_extractions"]] |
{
"list": [
{
"filename": "mainchain/dag_socket/server.py",
"retrieved_chunk": " file_send(conn, tips_file_addr)\n elif msg == 'uploadTx':\n conn.send('ok'.encode())\n recv_data = conn.recv(BUFFER_SIZE).decode()\n json_tx_data = json.loads(recv_data)\... | import os
import shutil
import pathlib
import dag_model.transaction as transaction
from dag_model.dag import DAG
from dag_socket import server
CACHE_DIR = "./cache/"
SERVER_DATA_DIR = pathlib.Path(CACHE_DIR) / "server"
TX_DATA_DIR = pathlib.Path(SERVER_DATA_DIR) / "txs"
DAG_DATA_DIR = pathlib.Path(SERVER_DATA_DIR) /... |
if __name__ == "__main__":
main() | {
"context_start_lineno": 0,
"file": "mainchain/server_run.py",
"groundtruth_start_lineno": 40,
"repository": "david-stan-dagfed-chain-0a60a23",
"right_context_start_lineno": 41,
"task_id": "project_cc_python/6681"
} | {
"list": [
{
"filename": "mainchain/dag_socket/server.py",
"retrieved_chunk": " file_send(conn, tips_file_addr)\n elif msg == 'uploadTx':\n conn.send('ok'.encode())\n recv_data = conn.recv(BUFFER_SIZE).decode()\n json_tx_data = json.loads(recv_data)\... | create_server_socket(server_dag) |
{
"list": [
{
"filename": "subchain/client.py",
"retrieved_chunk": " sys.exit(1)\n print(s.recv(1024).decode())\n data = 'uploadTx'.encode()\n s.send(data)\n response = s.recv(BUFFER_SIZE)\n data = json.dumps(tx_info).encode()\n s.send(data)\n s.close()\ndef rev_file(conn, ... | import socket
import threading
import sys
import struct
import os
import json
import pathlib
from dag_model.dag import DAG
import dag_model.transaction as transaction
BUFFER_SIZE = 1024
def create_server_socket(dag_obj, num_shards = 5):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s... |
dag_obj.tx_publish(new_tx)
print(f"The new block {new_tx.tx_name} has been published!")
conn.close() | {
"context_start_lineno": 0,
"file": "mainchain/dag_socket/server.py",
"groundtruth_start_lineno": 61,
"repository": "david-stan-dagfed-chain-0a60a23",
"right_context_start_lineno": 62,
"task_id": "project_cc_python/6683"
} | {
"list": [
{
"filename": "subchain/client.py",
"retrieved_chunk": " header = conn.recv(header_size)\n _, tx_size = struct.unpack('64si', header)\n print(f\"Size of the block is {tx_size}\")\n conn.send('header_resp'.encode())\n with open(tx_file_path, 'wb') as f:\n bytes_receive... | tx_save(new_tx) |
{
"list": [
{
"filename": "mainchain/dag_model/transaction.py",
"retrieved_chunk": "timestamp - timestamp of the block\nmodel_accuracy - accuracy of the aggregated model\nparam_hash - hash of the parameters file\n\"\"\"\nclass MainchainTransaction:\n def __init__(self,\n ... | import os
import shutil
import sys
import pathlib
import torch
import time
import uuid
import json
import random
import copy
import subprocess
import threading
import client
import fabric_api
sys.path.append('./ml')
sys.path.append('../')
# sys.path.append('../../commonComponent')
from ml.utils.settings import BaseS... |
# implement promise later
time.sleep(2)
with open("./cache/client/pools/tip_pool.json", 'r') as f:
tips_dict = json.load(f)
if len(tips_dict) <= alpha:
apv_tx_cands = list(tips_dict.keys())
else:
apv_tx_cands = random.sample(tips_dict... | {
"context_start_lineno": 0,
"file": "subchain/shard_run.py",
"groundtruth_start_lineno": 98,
"repository": "david-stan-dagfed-chain-0a60a23",
"right_context_start_lineno": 99,
"task_id": "project_cc_python/6685"
} | {
"list": [
{
"filename": "mainchain/dag_model/transaction.py",
"retrieved_chunk": " model_accuracy = 0.0,\n ) -> None:\n self.param_hash = param_hash\n self.timestamp = timestamp\n self.shard_id = shard_id\n self.approved_tips = approved_tips... | require_tips_from_server("localhost") |
{
"list": [
{
"filename": "subchain/fabric_api.py",
"retrieved_chunk": " \"\"\"\n localQuery = subprocess.Popen(args=[f\"./hyperledger_invoke.sh query_local {deviceID} {taskID}\"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')\n outs, errs = localQuery.communic... | import os
import shutil
import sys
import pathlib
import torch
import time
import uuid
import json
import random
import copy
import subprocess
import threading
import client
import fabric_api
sys.path.append('./ml')
sys.path.append('../')
# sys.path.append('../../commonComponent')
from ml.utils.settings import BaseS... |
t.start()
ts.append(t)
for t in ts:
t.join()
time.sleep(2)
flagList = flagList - flagSet
for deviceID in selectedDevices:
localFileName = f"./cache/client/local/{taskID}-{deviceID}-ep... | {
"context_start_lineno": 0,
"file": "subchain/shard_run.py",
"groundtruth_start_lineno": 218,
"repository": "david-stan-dagfed-chain-0a60a23",
"right_context_start_lineno": 219,
"task_id": "project_cc_python/6687"
} | {
"list": [
{
"filename": "subchain/federated_local.py",
"retrieved_chunk": " localParamHash, localAddStt = ipfsAddFile(localParamFile)\n if localAddStt == 0:\n print('%s has been added to the IPFS network!'%localParamFile)\n ... | query_local,args=(lock,taskID,deviceID,currentEpoch,flagSet,localFileName,)) |
{
"list": [
{
"filename": "src/data_io/data_loaders.py",
"retrieved_chunk": " self.data_dir = os.path.join(path, self.data_dir)\n self.train_data = np.memmap(os.path.join(self.data_dir, 'train.bin'), dtype=np.uint16, mode='r')\n self.val_data = np.memmap(os.path.join(self.data... | import os
from src.features.gpt_encoding import DataEncoder
def init_data(dataset, tmpdirname):
data_dir = os.path.join(tmpdirname, "data")
dataset_dir = os.path.join(data_dir, dataset)
os.mkdir(data_dir)
os.mkdir(dataset_dir)
train_data = "This is a dataset created for training loaders"
val... |
val_ids = data_encoder.encode(val_data)
data_encoder.save_data(val_ids, dir_path=dataset_dir, fname="val")
data_encoder.save_metadata(dir_path=dataset_dir)
| {
"context_start_lineno": 0,
"file": "test/shared/shared_testing.py",
"groundtruth_start_lineno": 15,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 16,
"task_id": "project_cc_python/6666"
} | {
"list": [
{
"filename": "src/data_io/data_loaders.py",
"retrieved_chunk": " meta = pickle.load(f)\n self.meta_vocab_size = meta['vocab_size']\n logger.info(f\"found vocab_size = {self.meta_vocab_size} (inside {meta_path})\")\n def get_batch(self, split):\n ... | save_data(train_ids, dir_path=dataset_dir, fname="train") |
{
"list": [
{
"filename": "test/unit/training/test_training.py",
"retrieved_chunk": " batch_size=job_config.batch_size,\n device=job_config.device,\n device_type=job_config.device_type,\n )\n data_loader = DataLoader(data_config, path=tmpdirname)\n model_config = GPTConfi... | import os
from tempfile import TemporaryDirectory
import pytest
from src.data_io.data_loaders import DataLoader, DataConfig
from src.features.gpt_encoding import DataEncoder
from test.shared.shared_testing import init_data
def test_load_metadata():
with TemporaryDirectory() as tmpdirname:
dataset = "tes... |
def test_get_batch():
with TemporaryDirectory() as tmpdirname:
dataset = "test_dataset"
batch_size = 2
block_size = 8
init_data(dataset, tmpdirname)
data_config = DataConfig(
dataset=dataset,
block_size=block_size,
batch_size=batch_size,... | {
"context_start_lineno": 0,
"file": "test/unit/data_io/test_data_loaders.py",
"groundtruth_start_lineno": 24,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 25,
"task_id": "project_cc_python/6657"
} | {
"list": [
{
"filename": "test/unit/training/test_training.py",
"retrieved_chunk": " bias=job_config.bias,\n vocab_size=None,\n dropout=job_config.dropout,\n )\n master_process = True\n seed_offset = 0\n job_config.gradient_accumulation_steps *= 8 # simulate 8 gpus\n... | meta_vocab_size == 50257 |
{
"list": [
{
"filename": "test/shared/shared_testing.py",
"retrieved_chunk": " train_ids = data_encoder.encode(train_data)\n data_encoder.save_data(train_ids, dir_path=dataset_dir, fname=\"train\")\n val_ids = data_encoder.encode(val_data)\n data_encoder.save_data(val_ids, dir_path=datase... | """
Prepare the Shakespeare dataset for language modeling.
"""
import os
import logging
import numpy as np
from src.features.gpt_encoding import DataEncoder
from src.data_io.data_fetchers import fetch_txt_data
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
"""
len... |
num_train_ids = train_ids["len"]
num_val_ids = val_ids["len"]
logger.info(f"train has {num_train_ids} tokens")
logger.info(f"val has {num_val_ids} tokens")
data_builder.save_data(train_ids, dir_path="data/tinyshakespeare", fname="train")
data_builder.save_data(val_ids, dir_path="data/tinys... | {
"context_start_lineno": 0,
"file": "src/data_io/fetch_shakespeare.py",
"groundtruth_start_lineno": 36,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 37,
"task_id": "project_cc_python/6670"
} | {
"list": [
{
"filename": "test/shared/shared_testing.py",
"retrieved_chunk": " train_ids = data_encoder.encode(train_data)\n data_encoder.save_data(train_ids, dir_path=dataset_dir, fname=\"train\")\n val_ids = data_encoder.encode(val_data)\n data_encoder.save_data(val_ids, dir_path=datase... | enc.n_vocab} tokens") |
{
"list": [
{
"filename": "src/data_io/fetch_shakespeare.py",
"retrieved_chunk": " num_val_ids = val_ids[\"len\"]\n logger.info(f\"train has {num_train_ids} tokens\")\n logger.info(f\"val has {num_val_ids} tokens\")\n data_builder.save_data(train_ids, dir_path=\"data/tinyshakespeare\", fna... | import os
from src.features.gpt_encoding import DataEncoder
def init_data(dataset, tmpdirname):
data_dir = os.path.join(tmpdirname, "data")
dataset_dir = os.path.join(data_dir, dataset)
os.mkdir(data_dir)
os.mkdir(dataset_dir)
train_data = "This is a dataset created for training loaders"
val... | {
"context_start_lineno": 0,
"file": "test/shared/shared_testing.py",
"groundtruth_start_lineno": 18,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 19,
"task_id": "project_cc_python/6667"
} | {
"list": [
{
"filename": "test/unit/features/test_gpt_encoding.py",
"retrieved_chunk": " text_data = \"This is a dataset created for testing encoder\"\n data_ids = data_encoder.encode(text_data, train=False)\n decoded_text = data_encoder.decode(data_ids)\n assert decoded_text == text_data... | save_metadata(dir_path=dataset_dir) | |
{
"list": [
{
"filename": "test/shared/shared_testing.py",
"retrieved_chunk": " train_ids = data_encoder.encode(train_data)\n data_encoder.save_data(train_ids, dir_path=dataset_dir, fname=\"train\")\n val_ids = data_encoder.encode(val_data)\n data_encoder.save_data(val_ids, dir_path=datase... | """
Prepare the Shakespeare dataset for language modeling.
"""
import os
import logging
import numpy as np
from src.features.gpt_encoding import DataEncoder
from src.data_io.data_fetchers import fetch_txt_data
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
"""
len... |
if __name__ == "__main__":
main()
| {
"context_start_lineno": 0,
"file": "src/data_io/fetch_shakespeare.py",
"groundtruth_start_lineno": 44,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 45,
"task_id": "project_cc_python/6672"
} | {
"list": [
{
"filename": "test/shared/shared_testing.py",
"retrieved_chunk": " train_ids = data_encoder.encode(train_data)\n data_encoder.save_data(train_ids, dir_path=dataset_dir, fname=\"train\")\n val_ids = data_encoder.encode(val_data)\n data_encoder.save_data(val_ids, dir_path=datase... | save_metadata(dir_path="data/tinyshakespeare") |
{
"list": [
{
"filename": "src/gptravel/core/travel_planner/travel_engine.py",
"retrieved_chunk": " return self.get_key_values_by_name(\"city\")\nclass TravelEngine(ABC):\n def __init__(self) -> None:\n self._regex = JsonExtractor()\n @abstractmethod\n def get_travel_plan_json(s... | import json
from abc import ABC, abstractmethod
from typing import Any, Dict, Optional
import openai
from gptravel.core.io.loggerconfig import logger
from gptravel.core.travel_planner.prompt import Prompt
from gptravel.core.travel_planner.travel_engine import TravelEngine, TravelPlanJSON
class OpenAITravelEngine(Tr... |
json_parsed_list = self._regex(message_response)
if len(json_parsed_list) > 1:
logger.warning("Found multiple json in travel planner response")
logger.debug("Regex complete successfully")
try:
json_object = json.loads(json_parsed_list[0])
except json.deco... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/travel_planner/openai_engine.py",
"groundtruth_start_lineno": 40,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 41,
"task_id": "project_cc_python/6650"
} | {
"list": [
{
"filename": "src/gptravel/core/travel_planner/travel_engine.py",
"retrieved_chunk": " return self.get_key_values_by_name(\"city\")\nclass TravelEngine(ABC):\n def __init__(self) -> None:\n self._regex = JsonExtractor()\n @abstractmethod\n def get_travel_plan_json(s... | debug("Applying regex on OpenAI GPT response") |
{
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " key: sum(item[key] for item in labeled_activities.values())\n for key in self._activities_labels\n }\n sum_scores = sum(aggregated_scores.values())\n aggregated_scores_norm... | import os
from abc import ABC, abstractmethod
from typing import Any, Dict, List
import requests
from dotenv import load_dotenv
from gptravel.core.io.loggerconfig import logger
from gptravel.core.services.engine.exception import HuggingFaceError
load_dotenv()
class TextClassifier(ABC):
def __init__(self, multi... |
raise HuggingFaceError
| {
"context_start_lineno": 0,
"file": "src/gptravel/core/services/engine/classifier.py",
"groundtruth_start_lineno": 69,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 70,
"task_id": "project_cc_python/6649"
} | {
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " logger.debug(\"ActivitiesDiversityScorer: score value = {}\".format(score))\n logger.debug(\n \"ActivitiesDiversityScorer: score weight = {}\".format(self._score_weight)\n )\n ... | error("Hugging Face classifier: error in retrieving API response") |
{
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " # the scorer evaluates the itinerary only if there are\n # more than two different visited city excluded the departure place\n if len(set(cities)) > 2:\n open_problem ... | from typing import List, Tuple
import numpy as np
from python_tsp.exact import solve_tsp_dynamic_programming
from python_tsp.heuristics import solve_tsp_simulated_annealing
from gptravel.core.io.loggerconfig import logger
from gptravel.core.services.geocoder import GeoCoder
class TSPSolver:
def __init__(self, g... |
logger.debug("TSP solver: solve the problem for cities = {}".format(cities))
logger.debug("TSP solver: open problem = {}".format(open_problem))
if len(cities) < 10:
solver = solve_tsp_dynamic_programming
logger.debug("TSP solver: use dynamic programmi... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/services/engine/tsp_solver.py",
"groundtruth_start_lineno": 23,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 24,
"task_id": "project_cc_python/6647"
} | {
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " if not open_problem:\n current_distance += solver.distance_matrix[0, -1]\n score = optimal_distance / current_distance\n logger.debug(\"CitiesCountrySc... | debug("TSP solver: start") |
{
"list": [
{
"filename": "src/inference/sample_main.py",
"retrieved_chunk": "def init_job(args):\n Configs = namedtuple(\"Configs\", \"job_config context\")\n job_args = parse_args(args)\n job_config = override_config(job_args.config_file, inference=True)\n torch.manual_seed(job_config.se... | import os
import logging
from collections import namedtuple
from contextlib import nullcontext
import torch
from src.config.configurator import override_config
from src.inference.inference_model import InferenceModel, InferenceModelInitialiser
logger = logging.getLogger(__name__)
class GPTServer:
"""This clas... |
return Configs(job_config, ctx)
def generate_sample(self, prompt_txt):
out = self.inference_model.generate_sample(prompt_txt)
return out
| {
"context_start_lineno": 0,
"file": "src/inference/gpt_server.py",
"groundtruth_start_lineno": 38,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 39,
"task_id": "project_cc_python/6679"
} | {
"list": [
{
"filename": "src/inference/sample_main.py",
"retrieved_chunk": " \"bfloat16\": torch.bfloat16,\n \"float16\": torch.float16,\n }[job_config.dtype]\n ctx = (\n nullcontext()\n if job_config.device_type == \"cpu\"\n else torch.amp.autocast(device_ty... | device_type == 'cpu' else torch.amp.autocast(device_type=job_config.device_type, dtype=ptdtype) |
{
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " ) -> None:\n logger.debug(\"CitiesCountryScorer: Start\")\n # remove departure place: check the consistence among the visiting cities\n unique_cities = list(\n set(travel_plan.trav... | from abc import ABC, abstractmethod
from gptravel.core.io.loggerconfig import logger
from gptravel.core.services.geocoder import GeoCoder
from gptravel.core.travel_planner.travel_engine import TravelPlanJSON
class Checker(ABC):
@abstractmethod
def check(self, travel_plan: TravelPlanJSON) -> bool:
pas... |
return all_exists
class DaysChecker(Checker):
def __init__(self, day_key: str = "Day") -> None:
self._travel_days = 0
self._day_key = day_key
@property
def travel_days(self) -> int:
return self._travel_days
def check(self, travel_plan: TravelPlanJSON) -> bool:
... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/services/checker.py",
"groundtruth_start_lineno": 31,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/6645"
} | {
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " for city in unique_cities\n ]\n latitude_score = abs(sum(latitude_signs)) / len(unique_cities)\n # Check cities are in the same country of the destination place\n destination_c... | warning("Check not passed") |
{
"list": [
{
"filename": "tests/test_gptravel/test_core/test_services/test_engine.py/test_classifier.py",
"retrieved_chunk": "import os\nimport pytest\nfrom gptravel.core.services.engine.classifier import ZeroShotTextClassifier\n@pytest.fixture()\ndef classifier() -> ZeroShotTextClassifier:\n retu... | import os
from abc import ABC, abstractmethod
from typing import Any, Dict, List
import requests
from dotenv import load_dotenv
from gptravel.core.io.loggerconfig import logger
from gptravel.core.services.engine.exception import HuggingFaceError
load_dotenv()
class TextClassifier(ABC):
def __init__(self, multi... |
response = requests.post(self._api_url, headers=headers, json=payload).json()
logger.debug("HuggingFace API fetching response: complete")
return response
def predict(
self,
input_text_list: List[str],
label_classes: List[str],
) -> Dict[str, Dict[str, float]]:
... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/services/engine/classifier.py",
"groundtruth_start_lineno": 42,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 43,
"task_id": "project_cc_python/6648"
} | {
"list": [
{
"filename": "tests/test_gptravel/test_core/test_services/test_engine.py/test_classifier.py",
"retrieved_chunk": " def test_property(self, classifier: ZeroShotTextClassifier):\n assert classifier.multi_label\n classifier.multi_label = False\n assert not classifier.... | debug("HuggingFace API fetching response: start") |
{
"list": [
{
"filename": "src/gptravel/core/travel_planner/travel_engine.py",
"retrieved_chunk": " return self.get_key_values_by_name(\"city\")\nclass TravelEngine(ABC):\n def __init__(self) -> None:\n self._regex = JsonExtractor()\n @abstractmethod\n def get_travel_plan_json(s... | import json
from abc import ABC, abstractmethod
from typing import Any, Dict, Optional
import openai
from gptravel.core.io.loggerconfig import logger
from gptravel.core.travel_planner.prompt import Prompt
from gptravel.core.travel_planner.travel_engine import TravelEngine, TravelPlanJSON
class OpenAITravelEngine(Tr... |
if len(json_parsed_list) > 1:
logger.warning("Found multiple json in travel planner response")
logger.debug("Regex complete successfully")
try:
json_object = json.loads(json_parsed_list[0])
except json.decoder.JSONDecodeError:
json_object = json.loads... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/travel_planner/openai_engine.py",
"groundtruth_start_lineno": 41,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 42,
"task_id": "project_cc_python/6651"
} | {
"list": [
{
"filename": "src/gptravel/core/travel_planner/travel_engine.py",
"retrieved_chunk": " return self.get_key_values_by_name(\"city\")\nclass TravelEngine(ABC):\n def __init__(self) -> None:\n self._regex = JsonExtractor()\n @abstractmethod\n def get_travel_plan_json(s... | _regex(message_response) |
{
"list": [
{
"filename": "src/gptravel/prototype/utils.py",
"retrieved_chunk": " cities: Union[List[str], Tuple[str]], destination: str\n) -> Dict[str, Tuple]:\n geo_coder = GeoCoder()\n logger.info(\"Get Cities coordinates: Start\")\n logger.debug(\"Get Cities coordinates: cities to anal... | import os
from functools import partial
from typing import Dict, List, Optional
from geopy import Location
from geopy.distance import geodesic as GRC
from geopy.extra.rate_limiter import RateLimiter
from geopy.geocoders import Photon
from gptravel.core.io.loggerconfig import logger
LOCATION_CACHE: Dict[str, Location... |
if loc_name in LOCATION_CACHE:
logger.debug("Using cached coordinates")
return LOCATION_CACHE[loc_name]
logger.debug("Downloading new Location for {}: Start".format(loc_name))
qry_obj = self._geocoder(location_name)
logger.debug("Downloading new Location for {}: ... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/services/geocoder.py",
"groundtruth_start_lineno": 27,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/6646"
} | {
"list": [
{
"filename": "tests/test_gptravel/test_core/test_services/test_checker.py",
"retrieved_chunk": " ) -> None:\n assert existing_cities_checker.check(travel_plan_single_city_per_day)\n def test_not_existing_destinations(\n self,\n existing_cities_checker: ExistingD... | debug("Querying coordinates for {}".format(loc_name)) |
{
"list": [
{
"filename": "src/gptravel/core/services/engine/classifier.py",
"retrieved_chunk": " headers = {\"Authorization\": f\"Bearer {self._api_token}\"}\n logger.debug(\"HuggingFace API fetching response: start\")\n response = requests.post(self._api_url, headers=headers, js... | import json
from abc import ABC, abstractmethod
from typing import Any, Dict, Optional
import openai
from gptravel.core.io.loggerconfig import logger
from gptravel.core.travel_planner.prompt import Prompt
from gptravel.core.travel_planner.travel_engine import TravelEngine, TravelPlanJSON
class OpenAITravelEngine(Tr... |
logger.debug("Regex complete successfully")
try:
json_object = json.loads(json_parsed_list[0])
except json.decoder.JSONDecodeError:
json_object = json.loads(
r"{}".format(json_parsed_list[0].replace("'", '"'))
)
return TravelPlanJSON(
... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/travel_planner/openai_engine.py",
"groundtruth_start_lineno": 43,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 44,
"task_id": "project_cc_python/6652"
} | {
"list": [
{
"filename": "src/gptravel/core/travel_planner/travel_engine.py",
"retrieved_chunk": " return self.get_key_values_by_name(\"city\")\nclass TravelEngine(ABC):\n def __init__(self) -> None:\n self._regex = JsonExtractor()\n @abstractmethod\n def get_travel_plan_json(s... | warning("Found multiple json in travel planner response") |
{
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " def __init__(self, geolocator: GeoCoder, score_weight: float = 1.0) -> None:\n service_name = \"City Countries\"\n super().__init__(service_name, score_weight)\n self._geolocator = geolocator... | from abc import ABC, abstractmethod
from gptravel.core.io.loggerconfig import logger
from gptravel.core.services.geocoder import GeoCoder
from gptravel.core.travel_planner.travel_engine import TravelPlanJSON
class Checker(ABC):
@abstractmethod
def check(self, travel_plan: TravelPlanJSON) -> bool:
pas... |
logger.debug("Check performed on cities: {}".format(city_list))
existing_cities = [
True
if self._geolocator.location_coordinates(city)["lat"] is not None
else False
for city in city_list
]
all_exists = all(existing_cities)
if all_... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/services/checker.py",
"groundtruth_start_lineno": 19,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 20,
"task_id": "project_cc_python/6644"
} | {
"list": [
{
"filename": "src/gptravel/core/services/scorer.py",
"retrieved_chunk": " if len(cities) > 2:\n logger.debug(\"CitiesCountryScorer: Start\")\n departure_place = travel_plan.departure_place\n cities = cities[1:] if cities[0] == departure_place.lower(... | debug("Check the existence of cities in the generated travel") |
{
"list": [
{
"filename": "src/gptravel/core/travel_planner/prompt.py",
"retrieved_chunk": " super().__init__(prompt, departure_place, destination_place, n_travel_days)\n @property\n def json_keys(self) -> Dict[str, int]:\n return {\"day\": 0, \"city\": 1}\nclass PromptFactory:\n ... | from abc import ABC, abstractmethod
import numpy as np
from gptravel.core.io.loggerconfig import logger
class TokenManager(ABC):
@abstractmethod
def get_number_tokens(self, **kwargs) -> int:
pass
class ChatGptTokenManager(TokenManager):
def __init__(self) -> None:
self._intercept = 382... |
logger.debug(
"Token Manager inputs: n_days = {}, travel_distance = {}".format(
kwargs["n_days"], kwargs["distance"]
)
)
n_tokens = int(
np.ceil(
max(
self._intercept
+ self._ndays_coef *... | {
"context_start_lineno": 0,
"file": "src/gptravel/core/travel_planner/token_manager.py",
"groundtruth_start_lineno": 20,
"repository": "RobertoCorti-gptravel-bcf49dd",
"right_context_start_lineno": 21,
"task_id": "project_cc_python/6653"
} | {
"list": [
{
"filename": "src/gptravel/core/travel_planner/prompt.py",
"retrieved_chunk": " ) -> None:\n prompt = f\"\"\"Generate a JSON with inside a travel plan of {n_travel_days} days for a person who wants to visit {destination_place} from\n {departure_place}. The structure of ... | debug("Computing max number of tokens for chatgpt engine") |
{
"list": [
{
"filename": "test/shared/shared_testing.py",
"retrieved_chunk": " train_ids = data_encoder.encode(train_data)\n data_encoder.save_data(train_ids, dir_path=dataset_dir, fname=\"train\")\n val_ids = data_encoder.encode(val_data)\n data_encoder.save_data(val_ids, dir_path=datase... | """
Prepare the Shakespeare dataset for language modeling.
"""
import os
import logging
import numpy as np
from src.features.gpt_encoding import DataEncoder
from src.data_io.data_fetchers import fetch_txt_data
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
"""
len... |
data_builder.save_data(val_ids, dir_path="data/tinyshakespeare", fname="val")
data_builder.save_metadata(dir_path="data/tinyshakespeare")
if __name__ == "__main__":
main()
| {
"context_start_lineno": 0,
"file": "src/data_io/fetch_shakespeare.py",
"groundtruth_start_lineno": 42,
"repository": "AlexGidiotis-gpt-light-ae75a5e",
"right_context_start_lineno": 43,
"task_id": "project_cc_python/6671"
} | {
"list": [
{
"filename": "test/shared/shared_testing.py",
"retrieved_chunk": " train_ids = data_encoder.encode(train_data)\n data_encoder.save_data(train_ids, dir_path=dataset_dir, fname=\"train\")\n val_ids = data_encoder.encode(val_data)\n data_encoder.save_data(val_ids, dir_path=datase... | save_data(train_ids, dir_path="data/tinyshakespeare", fname="train") |
{
"list": [
{
"filename": "tests/test_related_processors.py",
"retrieved_chunk": " def test_find_related_fields(self):\n attributes = get_report_attributes(\n ['name', 'sizes__name', 'sizes__picture__img', 'description__text'], Product\n )\n self.assertSetEqual(\n ... | from django.test import TestCase
from .models import Product, Size, Pic
from django_excel_report import BaseReport
class DefaultSettingsTests(TestCase):
@classmethod
def setUpTestData(cls):
p = Product.objects.create(name='p1', picture=Pic.objects.create(img='pic1'))
for i in range(5):
... |
def test_has_accessor_methods(self):
self.assertIsNotNone(getattr(self.report_class, 'get_name', None))
self.assertIsNotNone(getattr(self.report_class, 'get_sizes__name', None))
self.assertIsNotNone(getattr(self.report_class, 'get_sizes__picture__img', None))
self.assertIsNotNone(g... | {
"context_start_lineno": 0,
"file": "tests/test_base_report_attributes.py",
"groundtruth_start_lineno": 33,
"repository": "dichem-django-excel-report-686e1da",
"right_context_start_lineno": 34,
"task_id": "project_cc_python/6726"
} | {
"list": [
{
"filename": "tests/test_related_processors.py",
"retrieved_chunk": " def test_raises_error(self):\n self.assertRaises(\n ReportError,\n get_report_attributes,\n ['sizes'], Product\n )\n self.assertRaises(\n ReportError,\... | _select_related, set()) |
{
"list": [
{
"filename": "tests/test_report_get_row.py",
"retrieved_chunk": " model = Product\n fields = ['name', 'picture__img', 'sizes__name', 'sizes__picture__img']\n cls.report_class = TestReport(Product.objects.all())\n def test_find_related_fields(self):\n ... | from django.test import TestCase
from .models import Product, Size, Pic
from django_excel_report import BaseReport
class DefaultSettingsTests(TestCase):
@classmethod
def setUpTestData(cls):
p = Product.objects.create(name='p1', picture=Pic.objects.create(img='pic1'))
for i in range(5):
... |
self.assertSetEqual(self.empty_related_class._select_related, set())
def test_has_accessor_methods(self):
self.assertIsNotNone(getattr(self.report_class, 'get_name', None))
self.assertIsNotNone(getattr(self.report_class, 'get_sizes__name', None))
self.assertIsNotNone(getattr(self.r... | {
"context_start_lineno": 0,
"file": "tests/test_base_report_attributes.py",
"groundtruth_start_lineno": 32,
"repository": "dichem-django-excel-report-686e1da",
"right_context_start_lineno": 33,
"task_id": "project_cc_python/6725"
} | {
"list": [
{
"filename": "tests/test_report_get_row.py",
"retrieved_chunk": " model = Product\n fields = ['name', 'picture__img', 'sizes__name', 'sizes__picture__img']\n cls.report_class = TestReport(Product.objects.all())\n def test_find_related_fields(self):\n ... | _prefetch_related, set()) |
{
"list": [
{
"filename": "django_excel_report/writer/report_meta.py",
"retrieved_chunk": " if attrs[\"model\"] is None:\n raise ReportError(\"define model attr for %s class\" % name)\n elif attrs[\"fields\"] is None:\n raise ReportError(\"define report fields for %... | from typing import Iterable, Any
from django.db.models import QuerySet, Model
from django.core.files.base import ContentFile
from .writer import ReportMeta, Writer
from .error import ReportError
class BaseReport(metaclass=ReportMeta):
model: Model = None
fields: str | Iterable[str] | dict[str, Any] = None
... |
for obj in self:
writer.write_row(obj)
writer.wrap()
writer.save()
return writer.get_django_file()
def __iter__(self):
for obj in self.get_queryset():
yield self._get_row(obj)
def _get_row(self, obj: Model) -> list[str | list]:
return [g... | {
"context_start_lineno": 0,
"file": "django_excel_report/report.py",
"groundtruth_start_lineno": 29,
"repository": "dichem-django-excel-report-686e1da",
"right_context_start_lineno": 30,
"task_id": "project_cc_python/6712"
} | {
"list": [
{
"filename": "django_excel_report/writer/get_queryset_builder.py",
"retrieved_chunk": " return func(self).select_related(*select_related)\n return wrapper\n get_queryset = select_related_decorator(get_queryset)\n if prefetch_related:\n def prefet... | write_row([[field] for field in self.fields]) |
{
"list": [
{
"filename": "tests/test_base_report_attributes.py",
"retrieved_chunk": "from django.test import TestCase\nfrom .models import Product, Size, Pic\nfrom django_excel_report import BaseReport\nclass DefaultSettingsTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n p = ... | from django.test import TestCase
from django_excel_report import BaseReport
from .models import Product, Size, Pic
class DefaultSettingsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.product = p = Product.objects.create(name='p1', picture=Pic.objects.create(img='pic1'))
p.sizes.add... |
self.assertListEqual(
row,
[['p1'], ['pic1'], ['nopic', 'pic'], ['', '1']]
)
| {
"context_start_lineno": 0,
"file": "tests/test_report_get_row.py",
"groundtruth_start_lineno": 20,
"repository": "dichem-django-excel-report-686e1da",
"right_context_start_lineno": 21,
"task_id": "project_cc_python/6719"
} | {
"list": [
{
"filename": "tests/test_base_report_attributes.py",
"retrieved_chunk": " def setUpClass(cls):\n super().setUpClass()\n class ReportClass(BaseReport):\n model = Product\n fields = ['name', 'sizes__name', 'sizes__picture__img', 'description__text']\n ... | _get_row(self.product) |
{
"list": [
{
"filename": "eval.py",
"retrieved_chunk": " if not args.eval_only:\n pose_pr_list = []\n new_que_ids = []\n print(f\"obj number = {len(que_ids)}\")\n for idx, que_id in enumerate(tqdm(que_ids)):\n new_que_ids.append(que_i... | import argparse
from pathlib import Path
import cv2
import torch
from skimage.io import imsave
from tqdm import tqdm
from colmap_script import build_colmap_model_no_pose
from dataset.database import parse_database_name, get_database_split
from estimator import Gen6DEstimator
from network import name2network
from util... |
det_scale_r2q = inter_results['det_scale_r2q']
det_position = inter_results['det_position']
self_angle_r2q = inter_results['sel_angle_r2q']
ref_idx = inter_results['sel_ref_idx']
ref_pose = estimator.ref_info['poses'][ref_idx]
ref_K = estimator.ref_info['Ks'][ref_idx]
... | {
"context_start_lineno": 0,
"file": "prepare.py",
"groundtruth_start_lineno": 57,
"repository": "paulpanwang-Cas6D-245489d",
"right_context_start_lineno": 58,
"task_id": "project_cc_python/6733"
} | {
"list": [
{
"filename": "eval.py",
"retrieved_chunk": " if args.use_gt_box:\n gt_position, gt_scale_r2q, gt_angle_r2q, gt_ref_idx, gt_bbox, gt_scores = \\\n get_gt_info(pose_gt, K, estimator.ref_info['poses'], estimator.ref_info['Ks'], object_cent... | predict(img, K) |
{
"list": [
{
"filename": "estimator.py",
"retrieved_chunk": " scores = selection_results['scores'][:self.use_multi_pose_num]\n inter_results['sel_angle_r2q'] = angle_r2q\n inter_results['sel_scores'] = scores\n inter_results['sel_ref_idx'] =... | import argparse
from pathlib import Path
import cv2
import torch
from skimage.io import imsave
from tqdm import tqdm
from colmap_script import build_colmap_model_no_pose
from dataset.database import parse_database_name, get_database_split
from estimator import Gen6DEstimator
from network import name2network
from util... |
save_pickle(img_id2sel_info,f'data/val/sel/{que_database_name}/{estimator.detector.cfg["name"]}-{estimator.selector.cfg["name"]}.pkl')
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--action', type=str, required=True)
# for video2image
parser.add_argument('--inpu... | {
"context_start_lineno": 0,
"file": "prepare.py",
"groundtruth_start_lineno": 68,
"repository": "paulpanwang-Cas6D-245489d",
"right_context_start_lineno": 69,
"task_id": "project_cc_python/6735"
} | {
"list": [
{
"filename": "estimator.py",
"retrieved_chunk": " else:\n ref_idx = selection_results['ref_idx'][0]\n angle_r2q = selection_results['angles'][0] if angle_r2q is None else angle_r2q\n scores = selection_results['scores'][0]\n ... | detector.cfg["name"]}.pkl') |
{
"list": [
{
"filename": "core/_recording.py",
"retrieved_chunk": " data = noise_array\n greyscale_avg = navg * nproc\n if greyscale_avg > 1 and type(greyscale_avg) is int:\n avg_data = np.empty((int(data.shape[0] / g... | """
Helper script to generate images for recordings. Used by class `Recording`.
"""
import argparse
import struct
import sys
from PIL import Image
import numpy as np
import os
from . import _utils as utils
# from core import img_scale, data_clip
SNR_MIN = -10
SNR_MAX = 50
np.set_printoptions(threshold=sys.maxsize)
... |
avg_data = np.flip(utils.img_scale(avg_data, SNR_MIN, SNR_MAX),axis=0)
return avg_data
else:
utils.data_clip(data, SNR_MIN, SNR_MAX)
data = np.flip(utils.img_scale(data, SNR_MIN, SNR_MAX),axis=0)
return data
def data_IO_raw_compressed(fopen, npoints, nfft, navg, nproc, log... | {
"context_start_lineno": 0,
"file": "core/gen_pics.py",
"groundtruth_start_lineno": 34,
"repository": "sprite-neu-SPREAD-API-a2ee03a",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/6759"
} | {
"list": [
{
"filename": "core/_recording.py",
"retrieved_chunk": " break\n else:\n raise e\n else:\n avg_data = data\n avg_data = utils.da... | data_clip(avg_data, SNR_MIN, SNR_MAX) |
{
"list": [
{
"filename": "estimator.py",
"retrieved_chunk": " scores = selection_results['scores'][:self.use_multi_pose_num]\n inter_results['sel_angle_r2q'] = angle_r2q\n inter_results['sel_scores'] = scores\n inter_results['sel_ref_idx'] =... | import argparse
from pathlib import Path
import cv2
import torch
from skimage.io import imsave
from tqdm import tqdm
from colmap_script import build_colmap_model_no_pose
from dataset.database import parse_database_name, get_database_split
from estimator import Gen6DEstimator
from network import name2network
from util... |
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--action', type=str, required=True)
# for video2image
parser.add_argument('--input', type=str, default='example/video/mouse-ref.mp4')
parser.add_argument('--output', type=str, default='example/mouse/images')
pars... | {
"context_start_lineno": 0,
"file": "prepare.py",
"groundtruth_start_lineno": 69,
"repository": "paulpanwang-Cas6D-245489d",
"right_context_start_lineno": 70,
"task_id": "project_cc_python/6736"
} | {
"list": [
{
"filename": "estimator.py",
"retrieved_chunk": " else:\n ref_idx = selection_results['ref_idx'][0]\n angle_r2q = selection_results['angles'][0] if angle_r2q is None else angle_r2q\n scores = selection_results['scores'][0]\n ... | selector.cfg["name"]}.pkl') |
{
"list": [
{
"filename": "core/_annotation.py",
"retrieved_chunk": " (i.x_c + i.width / 2.0 - j.x_c - j.width / 2.0)) < 0:\n # Check beginning - end (this approach also merges overlapping transmissions in the same\n ... | """
Utils file that defines miscellaneous functions
"""
import math
import struct
from . import constants
import numpy as np
from random import choice
from PIL import Image
def pwr_to_db(pwr):
"""
Returns the power in dB
"""
return 10*math.log10(pwr)
def db_to_pwr(db_lvl):
"""
Returns the a... |
i_bw = constants.CHANNELS[i[0]][1]
i_range = (i_cf - i_bw / 2.0, i_cf + i_bw / 2.0)
j_cf = constants.CHANNELS[j[0]][0][j[1]]
j_bw = constants.CHANNELS[j[0]][1]
j_range = (j_cf - j_bw / 2.0, j_cf + j_bw / 2.0)
# print("%s %s" % ((i_range[0]-j_range... | {
"context_start_lineno": 0,
"file": "core/_utils.py",
"groundtruth_start_lineno": 233,
"repository": "sprite-neu-SPREAD-API-a2ee03a",
"right_context_start_lineno": 234,
"task_id": "project_cc_python/6758"
} | {
"list": [
{
"filename": "core/_annotation.py",
"retrieved_chunk": " # If inner for-loop breaks, break the outer for-loop in order to reconstruct the list and start over.\n break\n # When no more merging is needed\n else:\n # Break th... | CHANNELS[i[0]][0][i[1]] |
{
"list": [
{
"filename": "network/dino_detector.py",
"retrieved_chunk": " scores: qn,1,h/pn,w/pn\n select_pr_offset: qn,2,h/pn,w/pn\n select_pr_scale: qn,1,h/pn,w/pn\n select_pr_angle: qn,2,h/pn,w/pn # optional\n @return: all numpy ndarray\n ... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from network.operator import generate_coords, pose_apply_th
from pytorch3d.transforms import quaternion_apply
class Loss:
def __init__(self, keys):
"""
keys are used in multi-gpu model, DummyLoss in train_tools... |
center = center[:,:,None,None] # qn,2,h,w
labels = (torch.norm(coords-center,dim=1)<self.cfg['score_diff_thresh']).float() # qn,h,w
scores, labels = scores.flatten(1), labels.flatten(1) # [qn,h*w] [qn,h*w]
loss = self.loss_op(scores, labels)
loss_pos = torch.sum(loss * labels, ... | {
"context_start_lineno": 0,
"file": "network/loss.py",
"groundtruth_start_lineno": 39,
"repository": "paulpanwang-Cas6D-245489d",
"right_context_start_lineno": 40,
"task_id": "project_cc_python/6738"
} | {
"list": [
{
"filename": "network/dino_detector.py",
"retrieved_chunk": " position = torch.stack([score_x, score_y], -1) # qn,2\n # offset\n offset = results['select_pr_offset'][torch.arange(qn),:,score_y,score_x] # qn,2\n position = position + offset\n # to origin... | unsqueeze(0).repeat(qn,1,1,1).permute(0,3,1,2) # qn,2,h,w |
{
"list": [
{
"filename": "core/_annotation.py",
"retrieved_chunk": " try:\n self.label = int(label)\n self.x_c = max(min(float(x_c), 1.0), 0.0)\n self.y_c = max(min(float(y_c), 1.0), 0.0)\n self.width = max(min(float(width), 1.0), 0.0)\n s... | """
Utils file that defines miscellaneous functions
"""
import math
import struct
from . import constants
import numpy as np
from random import choice
from PIL import Image
def pwr_to_db(pwr):
"""
Returns the power in dB
"""
return 10*math.log10(pwr)
def db_to_pwr(db_lvl):
"""
Returns the a... |
else:
return "%sB" % size_bytes
def total_size(size_strs):
"""
Given a list of strings [1G, 500M, 2.5T] it calculates and returns a string with the total size
"""
size_sum = sum([convert_size(x, back=True) for x in size_strs if x])
try:
# Try to import hurry filesize f... | {
"context_start_lineno": 0,
"file": "core/_utils.py",
"groundtruth_start_lineno": 165,
"repository": "sprite-neu-SPREAD-API-a2ee03a",
"right_context_start_lineno": 166,
"task_id": "project_cc_python/6757"
} | {
"list": [
{
"filename": "core/_annotation.py",
"retrieved_chunk": " def left(self):\n \"\"\"Return the left border of the object region in the annotation\"\"\"\n return self.x_c - self.width / 2\n @property\n def right(self):\n \"\"\"Return the right border of the objec... | UNITS[size_bytes[-1]] if size_bytes != '0' else 0 |
{
"list": [
{
"filename": "network/dino_detector.py",
"retrieved_chunk": " @param ref_imgs: [an,rfn,h,w,3] in numpy\n @return:\n \"\"\"\n ref_imgs = torch.from_numpy(color_map_forward(ref_imgs)).permute(0,3,1,2) # rfn,3,h,w\n ref_imgs = ref_imgs.cuda()\n rfn, ... | import torch
import torch.nn as nn
import torchvision
import numpy as np
import torch.nn.functional as F
from loguru import logger
from network.attention import AttentionBlock
from network.pretrain_models import VGGBNPretrain
from utils.base_utils import color_map_forward
from network.vis_dino_encoder import VitExtract... |
ref_poses, object_center, object_vert = torch.from_numpy(ref_poses.astype(np.float32)).cuda(), \
torch.from_numpy(object_center.astype(np.float32)).cuda(), \
torch.from_numpy(object_vert.astype(np.float32)).cuda()
... | {
"context_start_lineno": 0,
"file": "network/selector.py",
"groundtruth_start_lineno": 203,
"repository": "paulpanwang-Cas6D-245489d",
"right_context_start_lineno": 204,
"task_id": "project_cc_python/6742"
} | {
"list": [
{
"filename": "network/detector.py",
"retrieved_chunk": " def detect_que_imgs(self, que_imgs):\n \"\"\"\n @param que_imgs: [qn,h,w,3]\n @return:\n \"\"\"\n que_imgs = torch.from_numpy(color_map_forward(que_imgs)).permute(0,3,1,2).contiguous().cuda()\n ... | transpose([0, 1, 4, 2, 3])).cuda() # an,rfn,3,h,w |
{
"list": [
{
"filename": "core/_recording.py",
"retrieved_chunk": " data = noise_array\n greyscale_avg = navg * nproc\n if greyscale_avg > 1 and type(greyscale_avg) is int:\n avg_data = np.empty((int(data.shape[0] / g... | """
Helper script to generate images for recordings. Used by class `Recording`.
"""
import argparse
import struct
import sys
from PIL import Image
import numpy as np
import os
from . import _utils as utils
# from core import img_scale, data_clip
SNR_MIN = -10
SNR_MAX = 50
np.set_printoptions(threshold=sys.maxsize)
... |
return avg_data
else:
utils.data_clip(data, SNR_MIN, SNR_MAX)
data = np.flip(utils.img_scale(data, SNR_MIN, SNR_MAX),axis=0)
return data
def data_IO_raw_compressed(fopen, npoints, nfft, navg, nproc, log_noise):
"""
IO from an FFT-ed complex recording file.
"""
bina... | {
"context_start_lineno": 0,
"file": "core/gen_pics.py",
"groundtruth_start_lineno": 35,
"repository": "sprite-neu-SPREAD-API-a2ee03a",
"right_context_start_lineno": 36,
"task_id": "project_cc_python/6760"
} | {
"list": [
{
"filename": "core/_recording.py",
"retrieved_chunk": " break\n else:\n raise e\n else:\n avg_data = data\n avg_data = utils.da... | img_scale(avg_data, SNR_MIN, SNR_MAX),axis=0) |
{
"list": [
{
"filename": "fid/fid_model.py",
"retrieved_chunk": " def eval(logstep: int):\n model.logstep = logstep\n summary = Summary()\n t0 = time.time()\n with torch.no_grad():\n fid = FID(FLAGS.dataset, (model.COLORS, model.params.res, model.params.res))... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
__all__ = ['TrainInfo', 'TrainModel', 'DistillModel']
import dataclasses
import json
import pathlib
import time
from types import SimpleNamespace
from typing import Callable, Dict, Iterable, List, Optional
import ... |
timesteps = self.params.timesteps >> self.logstep.item()
zip_batch_as_png(fake_samples, logdir / f'samples_{fid_len}_timesteps_{timesteps}.zip')
fidn, fid50 = fid.approximate_fid(fake_activations)
summary.scalar(f'eval/fid({fid_len})', fidn)
... | {
"context_start_lineno": 0,
"file": "lib/train.py",
"groundtruth_start_lineno": 97,
"repository": "apple-ml-tract-ad25296",
"right_context_start_lineno": 98,
"task_id": "project_cc_python/6783"
} | {
"list": [
{
"filename": "tc_distill.py",
"retrieved_chunk": " self.time_schedule = tuple(int(x) for x in self.params.time_schedule.split(','))\n steps_per_phase = int_str(FLAGS.train_len) / (FLAGS.batch * (len(self.time_schedule) - 1))\n ema = self.params.ema_residual ** (1 / st... | generate_activations_and_samples(self, FLAGS.fid_len) |
{
"list": [
{
"filename": "fid/compute_fid_stats.py",
"retrieved_chunk": "from lib.distributed import auto_distribute\nfrom lib.util import FLAGS, artifact_dir\nML_DATA = pathlib.Path(os.getenv('ML_DATA'))\n@auto_distribute\ndef main(argv):\n data = lib.data.DATASETS[FLAGS.dataset]()\n real = da... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
"""Compute FID and approximation at 50,000 for zip file of samples."""
import time
import zipfile
import lib
import torch
import torchvision.transforms.functional
from absl import app, flags
from lib.distributed imp... |
with torch.no_grad():
fid = lib.eval.FID(FLAGS.dataset, (3, data.res, data.res))
fake_activations = fid.data_activations(fake, FLAGS.fid_len)
fid, fid50 = fid.approximate_fid(fake_activations)
if is_master():
print(f'dataset={FLAGS.dataset}')
print(f'fid{FLAGS.fid_len}={... | {
"context_start_lineno": 0,
"file": "fid/fid_zip.py",
"groundtruth_start_lineno": 34,
"repository": "apple-ml-tract-ad25296",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/6779"
} | {
"list": [
{
"filename": "lib/io.py",
"retrieved_chunk": " return\n assert x.ndim == 4\n with zipfile.ZipFile(filename, 'w') as fzip:\n for i in range(x.shape[0]):\n with fzip.open(f'{i:06d}.png', 'w') as f:\n f.write(to_png(x[i]))",
"score": 46.090... | batch // world_size())) |
{
"list": [
{
"filename": "fid/compute_fid_stats.py",
"retrieved_chunk": "from lib.distributed import auto_distribute\nfrom lib.util import FLAGS, artifact_dir\nML_DATA = pathlib.Path(os.getenv('ML_DATA'))\n@auto_distribute\ndef main(argv):\n data = lib.data.DATASETS[FLAGS.dataset]()\n real = da... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
import os
import pathlib
from typing import Iterable, Tuple
import numpy as np
import scipy
import torch
import torch.nn.functional
from lib.distributed import (barrier, device_id, gather_tensor, is_master,
... |
self.dims = dims
self.shape = shape
self.model = InceptionV3([block_idx]).eval().to(device_id())
self.post = torch.nn.Sequential(torch.nn.AdaptiveAvgPool2d(1), torch.nn.Flatten())
if pathlib.Path(f'{ML_DATA}/{dataset}_activation_mean.npy').exists():
self.real_activat... | {
"context_start_lineno": 0,
"file": "lib/eval/fid.py",
"groundtruth_start_lineno": 25,
"repository": "apple-ml-tract-ad25296",
"right_context_start_lineno": 26,
"task_id": "project_cc_python/6796"
} | {
"list": [
{
"filename": "fid/compute_fid_stats.py",
"retrieved_chunk": " real_activations = fid.data_activations(real, num_samples, cpu=True)\n m_real, s_real = fid.calculate_activation_statistics(real_activations)\n np.save(f'{ML_DATA}/{FLAGS.dataset}_activation_mean.npy', m_real.n... | BLOCK_INDEX_BY_DIM[dims] |
{
"list": [
{
"filename": "tc_distill.py",
"retrieved_chunk": " if 'cifar' in name:\n self.ckpt_path = 'ckpts/cifar_original.pt'\n self.predict_both = False\n elif 'imagenet' in name:\n self.ckpt_path = 'ckpts/imagenet_original.pt'\n self.num_c... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
__all__ = ['TrainInfo', 'TrainModel', 'DistillModel']
import dataclasses
import json
import pathlib
import time
from types import SimpleNamespace
from typing import Callable, Dict, Iterable, List, Optional
import ... |
fake_activations, fake_samples = fid.generate_activations_and_samples(self, FLAGS.fid_len)
timesteps = self.params.timesteps >> self.logstep.item()
zip_batch_as_png(fake_samples, logdir / f'samples_{fid_len}_timesteps_{timesteps}.zip')
fidn, fid50 = fid.a... | {
"context_start_lineno": 0,
"file": "lib/train.py",
"groundtruth_start_lineno": 96,
"repository": "apple-ml-tract-ad25296",
"right_context_start_lineno": 97,
"task_id": "project_cc_python/6782"
} | {
"list": [
{
"filename": "tc_distill.py",
"retrieved_chunk": " self.time_schedule = tuple(int(x) for x in self.params.time_schedule.split(','))\n steps_per_phase = int_str(FLAGS.train_len) / (FLAGS.batch * (len(self.time_schedule) - 1))\n ema = self.params.ema_residual ** (1 / st... | dataset, (self.COLORS, self.params.res, self.params.res)) |
{
"list": [
{
"filename": "fid/fid_model.py",
"retrieved_chunk": " summary.scalar('eval/logstep', logstep)\n summary.scalar('eval/timesteps', timesteps)\n summary.scalar(f'eval/fid({FLAGS.fid_len})', fidn)\n summary.scalar('eval/fid(50000)', fid50)\n summary.scalar('... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
__all__ = ['TrainInfo', 'TrainModel', 'DistillModel']
import dataclasses
import json
import pathlib
import time
from types import SimpleNamespace
from typing import Callable, Dict, Iterable, List, Optional
import ... |
def train_step(self, summary: Summary, info: TrainInfo, batch: List[torch.Tensor]) -> None:
device = self.device
metrics = self.train_op(info, *[x.to(device, non_blocking=True) for x in batch])
summary.from_metrics(metrics)
| {
"context_start_lineno": 0,
"file": "lib/train.py",
"groundtruth_start_lineno": 156,
"repository": "apple-ml-tract-ad25296",
"right_context_start_lineno": 157,
"task_id": "project_cc_python/6792"
} | {
"list": [
{
"filename": "fid/fid_model.py",
"retrieved_chunk": " if FLAGS.denoise_steps:\n logstep = lib.util.ilog2(FLAGS.timesteps // FLAGS.denoise_steps)\n eval(logstep)\n else:\n for logstep in range(lib.util.ilog2(FLAGS.timesteps) + 1):\n ... | save_file(self.model_eval.module, 'model.ckpt') |
{
"list": [
{
"filename": "lib/eval/fid.py",
"retrieved_chunk": " activations = torch.empty((n, self.dims), dtype=torch.double).to(device_id())\n k = world_size()\n assert FLAGS.batch % k == 0\n for i in trange(0, n, FLAGS.batch, desc='Generating FID samples'):\n ... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
__all__ = ['TrainInfo', 'TrainModel', 'DistillModel']
import dataclasses
import json
import pathlib
import time
from types import SimpleNamespace
from typing import Callable, Dict, Iterable, List, Optional
import ... |
compute_fid = (samples % report_fid_len == 0) or (samples >= train_len)
self.evaluate(summary, logdir, ckpt, data_fid, fid_len=fid_len if compute_fid else 0,
sample_imgs=samples % report_img_len == 0)
t2 = time.time()
summary... | {
"context_start_lineno": 0,
"file": "lib/train.py",
"groundtruth_start_lineno": 146,
"repository": "apple-ml-tract-ad25296",
"right_context_start_lineno": 147,
"task_id": "project_cc_python/6790"
} | {
"list": [
{
"filename": "lib/eval/fid.py",
"retrieved_chunk": " activations[i: i + p] = gather_tensor(y)[:p]\n return activations, samples\n def data_activations(self, iterator: Iterable, n: int, cpu: bool = False) -> torch.Tensor:\n activations = torch.empty((n, self.dim... | scalar('sys/samples_per_sec_train', report_len / (t1 - t0)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.