Пример #1
0
class HCFlatten(layers.Layer):
    def __init__(self, **kwargs):
        super(HCFlatten, self).__init__(**kwargs)

    def build(self, input_shape):
        self.side_length = input_shape[1]
        if 2**math.log2(self.side_length) != self.side_length:
            raise
        dim = len(input_shape) - 2
        iters = int(math.log2(input_shape[1]))
        self.hc = HilbertCurve(n=dim, p=iters)

        self.side_length = input_shape[1]
        self.channel_dim = input_shape[-1]
        self.place_holder = tf.ones((self.side_length**2, 1))
        self.idxs = np.zeros(self.side_length**2, dtype='int')
        for i in range(self.side_length**2):
            x, y = self.hc.coordinates_from_distance(i)
            idx = x + self.side_length * y
            self.idxs[i] = idx

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.side_length**2, 1)

    def call(self, inputs):
        shape = (-1, self.side_length**2, self.channel_dim)
        inputs = tf.reshape(inputs, shape)

        def apply_gather(x):
            return tf.gather(x, self.idxs)

        #outputs = tf.reshape(tf.map_fn(apply_gather, inputs), shape + (1,))
        outputs = tf.map_fn(apply_gather, inputs)

        return outputs
def create_node_remap(nodes, channels_obj):
    N = 2
    p = math.ceil(math.log2(max(channels_obj.x_max, channels_obj.y_max)))

    point_map = {}

    for node in nodes:
        x = node.loc.x_low
        y = node.loc.y_low

        if (x, y) not in point_map:
            point_map[(x, y)] = []

        point_map[(x, y)].append(node.id)

    hilbert_curve = HilbertCurve(p, N)

    idx = 0
    id_map = {}
    for h in range(hilbert_curve.max_h + 1):
        coord = tuple(hilbert_curve.coordinates_from_distance(h))

        if coord not in point_map:
            continue

        for old_id in point_map[coord]:
            id_map[old_id] = idx
            idx += 1

        del point_map[coord]

    return lambda x: id_map[x]
Пример #3
0
def range2bbox(hlevel, query, dims=2, margin=0):

    hilbert_curve = HilbertCurve(hlevel, dims)
    inc = 0
    # ite = 0
    start = query["start"] + 1
    points = []
    if start % 4 is 1:
        points.append(start)
        start += 1
    if start % 4 is 2:
        points.append(start)
        start += 1
    if start % 4 is 3:
        points.append(start)
        start += 1
    points.append(start)

    # assume at this ppoint, start is always at the end of a level 0
    while start < query["end"] + 1:
        # ite += 1
        # print(inc)
        # locate the proper power incrementer
        # the incrementor indicates the maximum power of 4
        while start % (4**(inc + 1)) == 0:
            inc += 1
        while inc >= 0:
            # to get min x, min y, max x, max y, it is necessary to
            # locate the diagnol coordinates.
            # the 3rd point of the thrid sub-quadrons is always diagnol
            # to the starting point.
            if start + (4**inc) <= query["end"] + 1:
                points.append(start + 1)
                displacement = 0
                for x in range(inc - 1, -1, -1):
                    # the following lines are equivalent, and does not
                    # improve any speed
                    # displacement = displacement | (0b01 << (2 * x))
                    displacement += 2 * 4**x
                points.append(start + displacement + 1)
                start += 4**inc
                break
            else:
                inc = inc - 1

    # print(points)
    hillcorX = []
    hillcorY = []
    for point in points:
        [x, y] = hilbert_curve.coordinates_from_distance(point)
        # print(x, y, point)
        hillcorX.append(x)
        hillcorY.append(y)
    bbox = (min(hillcorX) - margin, min(hillcorY) - margin,
            max(hillcorX) + margin, max(hillcorY) + margin)
    # print(bbox)
    # print(time.time() - now)
    return bbox
Пример #4
0
 def load_code_linear(fileobj):
     code_helper = defaultdict(lambda: defaultdict(str))
     chars = "".join(char for line in fileobj for char in line.strip())
     p = (ceil(len(chars)**0.5) - 1).bit_length()
     hilbert = HilbertCurve(p, 2)
     for step, char in enumerate(chars):
         y, x = hilbert.coordinates_from_distance(step)
         code_helper[x][y] = char
     return code_helper, p
Пример #5
0
def RGBToImage (C, p, N):
    desired_size = 2**p
    im2 = Image.new("RGB", (desired_size , desired_size) , (255,255,255))
    hilbert_curve = HC(p, N)
    for i in range(4**p):
        coords = hilbert_curve.coordinates_from_distance(i)     #coords becomes a tuple, with an x and y value (in that order - which is why you take x coord = coords[0] and raw y = coords[1] - but then you have to change y to flip it and asjust it because the y axis goes from 0 to 99 and not 1 to 100)
        im2.putpixel((coords[0], (desired_size - coords[1] - 1)), (C[3*i],C[3*i+1],C[3*i+2]))
    pix = im2.load()
    PaddingColour2 = pix[0, 0]
    return [PaddingColour2, im2]
Пример #6
0
def hilbert_curve(p=12, n=2):
    hilbert_curve = HilbertCurve(p, n)
    coords = []
    i = 0
    while True:
        try:
            coords.append(hilbert_curve.coordinates_from_distance(i))
            i += 1
        except:
            break
    np.savez_compressed(f'hilvert_p{p}_n{n}.npz', np.array(coords))
Пример #7
0
def create_curve():
    hilbert_curve = HilbertCurve(4, 2)
    d = np.dtype(np.uint8)
    curve = np.empty((400, 2), dtype=d)
    reverse_curve = np.empty((20, 20), dtype=d)
    for i in range(9):
        curve[4 * i] = [2 * i, 0]
        curve[4 * i + 1] = [2 * i, 1]
        curve[4 * i + 2] = [2 * i + 1, 1]
        curve[4 * i + 3] = [2 * i + 1, 0]
    curve[36] = [18, 0]
    curve[37] = [19, 0]
    for i in range(9):
        curve[38 + 4 * i] = [19, 2 * i + 1]
        curve[38 + 4 * i + 1] = [18, 2 * i + 1]
        curve[38 + 4 * i + 2] = [18, 2 * i + 2]
        curve[38 + 4 * i + 3] = [19, 2 * i + 2]
    curve[74] = [19, 19]
    curve[75] = [18, 19]
    for i in range(8):
        curve[76 + 4 * i] = [17 - 2 * i, 19]
        curve[76 + 4 * i + 1] = [17 - 2 * i, 18]
        curve[76 + 4 * i + 2] = [17 - 2 * i - 1, 18]
        curve[76 + 4 * i + 3] = [17 - 2 * i - 1, 19]
    curve[108] = [1, 19]
    curve[109] = [0, 19]
    for i in range(8):
        curve[110 + 4 * i] = [0, 19 - 2 * i - 1]
        curve[110 + 4 * i + 1] = [1, 19 - 2 * i - 1]
        curve[110 + 4 * i + 2] = [1, 19 - 2 * i - 2]
        curve[110 + 4 * i + 3] = [0, 19 - 2 * i - 2]
    curve[142] = [0, 2]
    curve[143] = [1, 2]

    for i in range(256):
        curve[144 + i][0] = hilbert_curve.coordinates_from_distance(i)[0] + 2
        curve[144 + i][1] = hilbert_curve.coordinates_from_distance(i)[1] + 2
    '''for i in range(399):
		if (curve[i][0] != curve[i + 1][0] and curve[i][1] != curve[i + 1][1]):
			print("error: ", i)'''

    pic = np.zeros([400, 400, 3], dtype=np.uint8)

    for i in range(400):
        for j in range(10):
            for k in range(10):
                pic[20 * curve[i][0] + j + 5][20 * curve[i][1] + k +
                                              5][0] = int(i / 400 * 255)

    new_im = Image.fromarray(pic)
    new_im.save("../Misc/curve.png")

    #idx2numpy.convert_to_file("../MNIST/curve", curve)
Пример #8
0
def hilbert_idx(rows, cols):
    assert rows == cols, "Image must be square for Hilbert curve"
    assert (rows > 0
            and (rows & (rows - 1)) == 0), "Must have power-of-two sized image"
    order = int(np.log2(rows))
    curve = HilbertCurve(order, 2)
    idx = np.zeros((rows * cols, 2), dtype=np.int)
    for i in range(rows * cols):
        coords = curve.coordinates_from_distance(i)  # cols, then rows
        idx[i, 0] = coords[1]
        idx[i, 1] = coords[0]
    return idx
Пример #9
0
    def verify(self):
        """
        Verification with simple examples:
            1. Hilbert curve (should have fracDim=2)
            2. Randomly scattered points (should have fracDim=2)
            3. Straight line (should have fracDim=1)
        NOTE: Computing example 1 requires hilbertcurve package

        Returns
        -------
        veri : List of floats
            List containing metric(s) for verification case.

        """
        from hilbertcurve.hilbertcurve import HilbertCurve

        # 1. Hilbert curve (should have fracDim=2)
        t1 = np.zeros((512, 512))
        pHil = 8
        nHil = 2
        dist = 2 ** (pHil * nHil)
        hilbert_curve = HilbertCurve(pHil, nHil)
        coords = np.zeros((dist, nHil))
        for i in range(dist):
            coords[i, :] = hilbert_curve.coordinates_from_distance(i)
        coords = coords.astype(int)
        coords *= 2
        coordsAv = (coords[1:, :] + coords[:-1, :]) / 2
        coordsAv = coordsAv.astype(int)
        t1[coords[:, 0], coords[:, 1]] = 1
        t1[coordsAv[:, 0], coordsAv[:, 1]] = 1

        # 2. Random points (should have fracDim=2)
        t2 = np.random.rand(512, 512)
        ind = np.where(t2 > 0.5)
        t2[ind] = 1
        ind = np.where(t2 <= 0.5)
        t2[ind] = 0

        # 3. Vertical line (should have fracDim=1)
        t3 = np.zeros((512, 512))
        t3[:, 250:252] = 1
        tests = [t1, t2, t3]

        veri = []
        for i in range(len(tests)):
            fracDim = self.metric(tests[i])
            veri.append(fracDim)

        return veri
Пример #10
0
 def convert1dto2d(x):
     """
         x = [N, 1024, 3]
         return [N, 32, 32, 3]
     """
     N = x.shape[0]
     hilbert_curve = HilbertCurve(5, 2)
     s = np.zeros((N, 32, 32, 3))
     cells = [hilbert_curve.coordinates_from_distance(d) for d in range(1024)]
     for k in range(N):
         for d in range(1024):
             i = cells[d][0]
             j = cells[d][1]
             s[k, i, j, :] = x[k, d, :]
     return s
Пример #11
0
def range2bbox(hlevel, query, dims=2):
    # query = {
    #     "start": 0,
    #     "end":  127074
    #     }
    hilbert_curve = HilbertCurve(hlevel, dims)
    inc = 0
    # ite = 0
    start = query["start"] + 1
    points = []
    if start % 4 is 1:
        points.append(start)
        start += 1
    if start % 4 is 2:
        points.append(start)
        start += 1
    if start % 4 is 3:
        points.append(start)
        start += 1
    points.append(start)

    # assume at this ppoint, start is always at the end of a level 0
    while start < query["end"] + 1:
        # ite += 1
        # print(inc)
        # locate the proper power incrementer
        while start % (4**(inc + 1)) == 0:
            inc += 1
        while inc >= 0:
            if start + (4**inc) <= query["end"] + 1:
                points.append(start + 1)
                points.append(start + (4**inc))
                start += 4**inc
                break
            else:
                inc = inc - 1

    # print(points)
    hillcorX = []
    hillcorY = []
    for point in points:
        [x, y] = hilbert_curve.coordinates_from_distance(point)
        hillcorX.append(x)
        hillcorY.append(y)
    bbox = (min(hillcorX), min(hillcorY), max(hillcorX), max(hillcorY))
    # print(bbox)
    return bbox
Пример #12
0
 def decode_sfc(codes, M=3, p=10):
     """
         codes = [N, D]
     """
     hilbert_curve = HilbertCurve(p, M)
     num_points = 2 ** (M*p) - 1
     grid_size = 2**p - 1
     N = codes.shape[0]
     D = codes.shape[1]
     s = np.zeros((N, D, M))
     for i in range(N):
         for j in range(D):
             v = int(codes[i, j] * num_points)
             coords = hilbert_curve.coordinates_from_distance(v)
             # p bins each coordinate
             s[i, j, :] = np.asarray(coords) / grid_size
     return s
Пример #13
0
    def __init__(self):
        super(HilbertNet, self).__init__()
        self.conv1 = nn.Conv1d(1, 32, 3, 1, padding=1)
        self.conv2 = nn.Conv1d(32, 64, 3, 1, padding=1, dilation=1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(16384, 128)
        # self.fc1 = nn.Linear(8192, 128)
        # self.fc1 = nn.Linear(4096, 128)
        self.fc2 = nn.Linear(128, 10)

        h, w = 32, 32
        N = 2
        p = int(log2(h * w))
        hilbert_curve = HilbertCurve(p, N)
        self.indexes = np.transpose([
            hilbert_curve.coordinates_from_distance(ii)
            for ii in range(2**p)
        ])
Пример #14
0
def test_coordinates_from_distance(p, n):
    # Build vector of possible distances
    distances = np.arange(2**(n * p), dtype=np.int64)

    # Compute coordinates as vector result
    vector_result = coordinates_from_distances(p, n, distances)

    # Compare with reference
    reference_hc = HilbertCurve(p, n)
    for i, distance in enumerate(distances):
        # Reference
        expected = tuple(reference_hc.coordinates_from_distance(distance))

        # Scalar result
        scalar_result = tuple(coordinate_from_distance(p, n, distance))
        assert scalar_result == expected

        # Vector result
        assert tuple(vector_result[i, :]) == expected
Пример #15
0
def main(input_file, output_file):
    plt.figure(figsize=(10, 10))
    packets = rdpcap(input_file)

    packet_times = []
    packet_time_min = None

    for packet in packets:
        # lib doesn't support float
        packet_time = int(packet.time * 1000000)
        packet_times.append(packet_time)

        if packet_time_min is None:
            packet_time_min = packet_time
        elif packet_time < packet_time_min:
            packet_time_min = packet_time

    # convert to relative
    relative_packet_times = [
        packet_time - packet_time_min for packet_time in packet_times
    ]

    for p in range(1, max_p):
        hc = HilbertCurve(p, N)
        pts = []

        try:
            for packet_time in relative_packet_times:
                pts.append(hc.coordinates_from_distance(packet_time))
        except ValueError:
            continue

        print(f'Computing with N={N}, p={p}')

        for i in range(len(pts) - 1):
            plt.scatter(pts[i][0], pts[i][1], 60, color=color)
        break

    plt.xlabel('x')
    plt.ylabel('y')
    plt.tight_layout()
    plt.savefig(output_file)
Пример #16
0
def hilbert_dithering(im_in, thresholds=[0, 255], verbose=True):
    im_out = im_in.copy()
    im_width, im_height = im_out.size
    p = ceil(log2(max(im_width, im_height)))
    if im_out.mode in ('RGB', 'RGBA'):
        ch = 3
    if im_out.mode in ('L', 'LA'):
        ch = 1
    if verbose:
        print('picture size:', im_width, im_height)
        print('p-size:', p)
        print('channels:', ch)
    n = 2
    h = HilbertCurve(p, n)
    err = [0] * ch
    for i in range(2**(p * n) - 1):
        # for i in range(500):
        coords = h.coordinates_from_distance(i)
        if coords[0] < im_width and coords[1] < im_height:
            new_pixel = [0] * ch + [255]
            for j in range(ch):
                current_v = im_out.getpixel(tuple(coords))[j]
                prev_t = thresholds[0]
                prev_score = abs(current_v + err[j] - prev_t)
                new_v = 0
                for t in thresholds:
                    score = abs(current_v + err[j] - t)
                    if score > prev_score:
                        new_v = prev_t
                        break
                    prev_score = score
                    prev_t = t
                    new_v = t
                new_pixel[j] = new_v
                err[j] += current_v - new_v
            new_pixel = tuple(new_pixel)
            im_out.putpixel(coords, new_pixel)
    return im_out
Пример #17
0
def ImageToRGB(im):

    old_size = im.size  # old_size[0] is in (width, height) format
    old_resolution = old_size[0]*old_size[1]

    N=2
    p = math.ceil(math.log(old_resolution,2)/2)

    desired_size = 2**p

    PaddingColour1 = PaddingColour(im, p, N)
    new_im = Image.new("RGB", (desired_size, desired_size), PaddingColour1) ##third thing - colour - here it's left blank so that automatically makes the padding area black
    new_im.paste(im, ((desired_size-old_size[0])//2,(desired_size-old_size[1])//2))
    pix = new_im.load()

    C = [0]*((4**p)*3)

    hilbert_curve = HC(p, N)
    
    
    for i in range(4**p):
        coords = hilbert_curve.coordinates_from_distance(i)
        C[3*i], C[3*i+1], C[3*i+2] = pix[coords[0], (desired_size - coords[1] - 1)]
    return (C, p, N, new_im)
Пример #18
0
class TBGenomicsDataset(Dataset):
    """ Dataset object used to access the TB-Genomics Dataset """
    def __init__(self, path, shuffle=False, transform=None, subset_size=None):
        """
        Instantiates the Dataset.

        :param root: Path to the folder where the pre-processed dataset is stored.
        :param shuffle: If True, the video files will be shuffled.
        :param transform: Transformations to be done to all frames of the video files.
        """
        self.transform = transform

        self.file = pd.read_csv(path).values.astype(int)
        self.length = self.file.shape[1]
        self.indexes = [idx for idx in range(self.length)]
        (self.p, self.N) = self.hilbert_params(self.file)
        self.hbc = HilbertCurve(self.p, self.N)
        if shuffle:
            random.shuffle(self.indexes)

        if subset_size is not None:
            self.k = int(subset_size)

    def __len__(self):
        return self.length

    def __getitem__(self, idx):

        #get the data
        real_idx = self.indexes[idx]
        real = self.file[:, real_idx].reshape(self.file.shape[0], 1)
        m = np.random.randint(1, self.length, size=(self.k, ))
        while real_idx in m:
            m = np.random.randint(1, self.length, size=(self.k, ))

        rest = (self.file[:, m])
        rest = np.concatenate((rest, real), axis=1).T
        rest = pd.DataFrame(rest).values

        # temporary params
        C = 1
        H = np.power(2, int(self.p))
        k = rest.shape[0]
        W = np.power(2, int(self.p))

        # convert data from 1D to 2D using hilber transform
        rest = rest.reshape(k, -1)
        data = []
        index = []
        rest_int = rest.astype(int)
        for i in rest_int:
            zero = np.zeros(shape=(H, W))
            coords = []
            for j in i:
                coords.append(self.hbc.coordinates_from_distance(j))

            for index, val in enumerate(rest[i]):
                zero[coords[i][0], coords[i][1]] = val

            index.append(coords)
            data.append(zero)

        data = np.array(data)
        data = data.reshape(k, 1, C, H, W)
        data = torch.from_numpy(data)
        data = torch.cat((data, data), dim=1)

        return real_idx, (data, index)

    def hilbert_params(self, a):
        """
            Get parameters for Hilbert curve representation
        """
        maxv = np.max(a)
        # N = dimensions
        N = 2

        # p = number of iterations
        #
        # 2^(N*p)-1 >= maxv
        # 2^(N*p) >= (maxv + 1)
        # N*p >= log( (maxv + 1), 2 )
        # p >= (1/N) * log( (maxv + 1), 2 )
        p = np.ceil((1 / N) * np.log2(maxv + 1))
        p = max(8, p)
        return (p, N)
Пример #19
0
from hilbertcurve.hilbertcurve import HilbertCurve

# we can go from distance along a curve to coordinates
# in 2 dimensions with p=1 there are only 4 locations on the curve
# [0, 0], [0, 1], [1, 1], [1, 0]
p = 1
N = 2
hilbert_curve = HilbertCurve(p, N)
for ii in range(4):
    print('coords(h={},p={},N={}) = {}'.format(
        ii, p, N, hilbert_curve.coordinates_from_distance(ii)))

# due to the magic of arbitrarily large integers in
# Python (https://www.python.org/dev/peps/pep-0237/)
# these calculations can be done with absurd numbers
p = 512
N = 10
hilbert_curve = HilbertCurve(p, N)
ii = 123456789101112131415161718192021222324252627282930
coords = hilbert_curve.coordinates_from_distance(ii)
print('coords(h={},p={},N={}) = {}'.format(ii, p, N, coords))
Пример #20
0
def Hilbert_Mapping_Inverse(h, p=8, dim=10):
    hilbert_curve = HilbertCurve(p, dim)
    aa = hilbert_curve.coordinates_from_distance(int(h * 2**(p * dim)))
    aa = np.array(aa) + 0.5
    aa = aa / (2**p)
    return aa
Пример #21
0
#!/usr/bin/env python

from BitVector import BitVector
from PIL import Image
from hilbertcurve.hilbertcurve import HilbertCurve
import sys
import math

img = Image.open(sys.argv[1])

# build a list of hilbert curve coordinates
hc = HilbertCurve(int(math.log2(img.height)), 2)
locations = [hc.coordinates_from_distance(i) for i in range(hc.max_h + 1)]

# iterate the pixels in transposed hilbert curve order
bitlist = [img.getpixel((y, x))[2] & 1 for (x, y) in locations]
BitVector(bitlist=bitlist).write_to_file(open("out.png", "wb"))

Image.open("out.png")
# from math import log
# from itertools import izip
# from string import printable
# from re import findall

# def grouped(iterable, n):
#     "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
#     return izip(*[iter(iterable)]*n)

# def dtoxy(n, d):
#     t = d
#     rx = ry = x = y = 0
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
import numpy as np
from hilbertcurve.hilbertcurve import HilbertCurve

N = 3
p = 3
hc = HilbertCurve(p, N)
npts = 2**(N * p)
pts = []
for i in range(npts):
    pts.append(hc.coordinates_from_distance(i))

x = [pt[0] for pt in pts]
y = [pt[1] for pt in pts]
z = [pt[2] for pt in pts]

fig = plt.figure(figsize=(10, 10))
ax = fig.gca(projection='3d')


def init():
    s = 1
    cmap = cm.nipy_spectral
    for i in range(0, npts - s, s):
        if (i + 1) % 8 == 0:
            linestyle = '--'
            linewidth = 1
Пример #23
0
def hcoords(x, chromLength, dims=2):
    hlevel = math.ceil(math.log2(chromLength) / dims)
    print("hlevel, ", hlevel)
    hilbert_curve = HilbertCurve(hlevel, dims)
    [x, y] = hilbert_curve.coordinates_from_distance(x)
    return x, y, hlevel
Пример #24
0
from hilbertcurve.hilbertcurve import HilbertCurve
from matplotlib.pyplot import *
p = 8
N = 2
hill_curve = HilbertCurve(p, N)

num_coords = 256 * 4
y_coords = []
x_coords = []
coords = []

for i in range(num_coords):
    hil_coords = hill_curve.coordinates_from_distance(i)
    coords.append(hil_coords)
    x_coords.append(hil_coords[0])
    y_coords.append(hil_coords[1])
plot(x_coords, y_coords)
show()
print(coords)
Пример #25
0
class Aceto:
    """ Interpreter object """
    def __init__(self, verbosity, flushness, allerr, encoding):
        self.stacks = defaultdict(list)
        self.sticky = set()
        self.sid = 0
        self.quick = ""
        self.verbosity = verbosity
        self.flushness = flushness
        self.allerr = allerr
        self.encoding = encoding
        # annotate this!
        self.commands = self.get_annotations()

    def get_annotations(self):
        cmds = {}
        d = type(self).__dict__
        for key in d:
            try:
                chars = d[key].__annotations__["return"]
                for c in chars:
                    cmds[c] = d[key]
            except KeyError:
                pass
            except AttributeError:
                pass
        return cmds

    def print_commands(self):
        cols, _ = shutil.get_terminal_size((80, 20))
        info = [f"{c} {f.__name__[1:]}" for c, f in self.commands.items()]
        info.sort()
        maxlen = max(len(x) for x in info) + 1
        columns = cols // maxlen
        iinfo = iter(info)
        end_character = "" if sys.stdout.isatty() else "\n"
        try:
            while True:
                for _ in range(columns):
                    item = next(iinfo)
                    # skip all numbers except for 0
                    while item.startswith(tuple("123456789")):
                        item = next(iinfo)
                    print(item.ljust(maxlen), end=end_character)
                if not end_character:
                    print()
        except StopIteration:
            print()

    @staticmethod
    def load_code_linear(fileobj):
        code_helper = defaultdict(lambda: defaultdict(str))
        chars = "".join(char for line in fileobj for char in line.strip())
        p = (ceil(len(chars)**0.5) - 1).bit_length()
        hilbert = HilbertCurve(p, 2)
        for step, char in enumerate(chars):
            y, x = hilbert.coordinates_from_distance(step)
            code_helper[x][y] = char
        return code_helper, p

    @staticmethod
    def load_code_hilbert(fileobj):
        code = []
        for line in reversed(fileobj.readlines()):
            code.append(list(line.rstrip("\n")))
        return code, (max(len(code), max(map(len, code))) - 1).bit_length()

    def load_code(self, filename, linear_mode=False):
        with open(filename, encoding=self.encoding) as f:
            if linear_mode:
                self.code, self.p = self.load_code_linear(f)
            else:
                self.code, self.p = self.load_code_hilbert(f)
        self.s = 2**self.p
        self.x, self.y = 0, 0
        self.timestamp = time.time()
        self.catch_mark = None
        self.dir = 1
        self.buf = ""
        self.mode = "command"
        self.previous_cmd = " "
        self.hilbert = HilbertCurve(self.p, 2)  # side length p, 2 dimensions

    def run(self):
        while True:
            try:
                self.step()
            except Exception as e:
                if self.catch_mark is not None and not self.allerr:
                    self.log(2, "Caught", e)
                    self.x, self.y = self.catch_mark
                else:
                    raise e

    def push(self, thing):
        self.stacks[self.sid].append(thing)

    def pushiter(self, iterable):
        self.stacks[self.sid].extend(iterable)

    def pop(self):
        try:
            x = self.stacks[self.sid][-1]
            if self.sid not in self.sticky:
                self.stacks[self.sid].pop()
            return x
        except IndexError:
            return 0

    def log(self, level, *pargs, **kwargs):
        if level <= self.verbosity:
            print(Colors.FAIL.value, file=sys.stderr, end="")
            print(*pargs, file=sys.stderr, **kwargs)
            print(Colors.ENDC.value, file=sys.stderr, end="", flush=True)

    def next_coord(self):
        """Return the next coordinate"""
        distance = self.hilbert.distance_from_coordinates([self.y, self.x])
        y, x = self.hilbert.coordinates_from_distance(distance + self.dir)
        return x, y

    def step_command_mode(self, cmd):
        method = self.commands.get(cmd, Aceto._nop)
        method(self, cmd)
        self.previous_cmd = cmd

    def step_string_mode(self, cmd):
        if cmd == '"' and self.mode == "string":
            self.push(self.buf)
            self.buf = ""
            self.mode = "command"
        elif cmd == "\\" and self.mode == "string":
            self.mode = "string-escape"
        elif self.mode == "string-escape" and cmd in "nt":
            self.buf += {"n": "\n", "t": "\t"}[cmd]
            self.mode = "string"
        else:
            self.buf += cmd
            self.mode = "string"
        self.move()

    def step_char_mode(self, cmd):
        if cmd == "\\" and self.mode == "char":
            self.mode = "char-escape"
        elif self.mode == "char-escape" and cmd in "nt":
            self.push({"n": "\n", "t": "\t"}[cmd])
            self.mode = "command"
        else:
            self.push(cmd)
            self.mode = "command"
        self.move()

    def step_escape_mode(self, cmd):
        self.move()
        self.mode = "command"

    def get_command(self):
        try:
            return self.code[self.x][self.y]
        except IndexError:
            return " "  # nop

    def step(self):
        cmd = self.get_command()
        if cmd != " ":
            self.log(1, cmd, end="")
            self.log(2, "\nActive stack:", self.stacks[self.sid])
        if self.mode == "command":
            self.step_command_mode(cmd)
        elif self.mode in ("string", "string-escape"):
            self.step_string_mode(cmd)
        elif self.mode in ("char", "char-escape"):
            self.step_char_mode(cmd)
        elif self.mode == "escape":
            self.step_escape_mode(cmd)
        else:
            raise CodeException("Invalid mode:", self.mode)

    def move(self, coords=None):
        if coords is not None:
            x, y = coords
        else:
            if self.dir == -1 and (0, 0) == (self.x, self.y):
                x, y = -1, -1
            else:
                try:
                    x, y = self.next_coord()
                except ValueError:
                    sys.exit()
        if x >= 2**self.p or y >= 2**self.p or x < 0 or y < 0:
            sys.exit()
        self.x, self.y = x, y

    def _nop(self, cmd) -> " ":
        self.move()

    def _left(self, cmd) -> "<W":
        if cmd == "W":
            self.code[self.x][self.y] = "N"
        self.move((self.x, (self.y - 1) % self.s))

    def _right(self, cmd) -> ">E":
        if cmd == "E":
            self.code[self.x][self.y] = "S"
        self.move((self.x, ((self.y + 1) % self.s)))

    def _down(self, cmd) -> "vS":
        if cmd == "S":
            self.code[self.x][self.y] = "W"
        self.log(
            2,
            f"{self.s} From {self.x},{self.y} to "
            f"{(self.x - 1) % self.s}, {self.y}",
        )
        self.move(((self.x - 1) % self.s, self.y))

    def _up(self, cmd) -> "^N":
        if cmd == "N":
            self.code[self.x][self.y] = "E"
        self.move(((self.x + 1) % self.s, self.y))

    def _numeric(self, cmd) -> "1234567890":
        self.push(int(cmd))
        self.move()

    def _plus(self, cmd) -> "+":
        x = self.pop()
        y = self.pop()
        try:
            self.push(y + x)
            self.move()
        except TypeError:
            raise CodeException(f"Can't add {x!r} to {y!r}")

    def _pow__find_char(self, cmd) -> "F":
        x = self.pop()
        y = self.pop()
        if isinstance(y, Number):
            try:
                self.push(y**x)
            except TypeError:
                raise CodeException(f"Can't raise {y!r} to the power of {x!r}")
        else:
            try:
                self.push(y[x])
            except IndexError:
                raise CodeException("Index out of range")
        self.move()

    def _minus__split1(self, cmd) -> "-":
        x = self.pop()
        if isinstance(x, Number):
            y = self.pop()
            try:
                self.push(y - x)
            except TypeError:
                raise CodeException(f"Can't subtract {x!r} from {y!r}")
        else:
            self.pushiter(reversed(x.split()))
        self.move()

    def _times(self, cmd) -> "*":
        x = self.pop()
        y = self.pop()
        try:
            self.push(y * x)
            self.move()
        except TypeError:
            raise CodeException(f"Can't multiply {x!r} with {y!r}")

    def _mod__re_replace(self, cmd) -> "%":
        x = self.pop()
        y = self.pop()
        if isinstance(x, Number):
            try:
                self.push(y % x)
            except TypeError:
                raise CodeException(f"Can't get modulo of {y!r} and {x!r}")
        else:
            z = self.pop()
            self.push(re.sub(y, z, x))
        self.move()

    def _div__re_matches(self, cmd) -> "/":
        x = self.pop()
        y = self.pop()
        if isinstance(x, Number):
            try:
                self.push(y // x)
            except ZeroDivisionError:
                raise CodeException("Zero division")
            except TypeError:
                raise CodeException(f"Can't idivide {y!r} by {x!r}")
        else:
            self.push(len(re.findall(y, x)))
        self.move()

    def _floatdiv__split2(self, cmd) -> ":":
        x = self.pop()
        if isinstance(x, Number):
            y = self.pop()
            try:
                self.push(y / x)
            except ZeroDivisionError:
                raise CodeException("Zero division")
            except TypeError:
                raise CodeException(f"Can't fdivide {y!r} by {x!r}")
        else:
            y = self.pop()
            self.pushiter(reversed(y.split(x)))
        self.move()

    def _equals(self, cmd) -> "=":
        x = self.pop()
        y = self.pop()
        self.log(2, f"Testing equality of {x!r} and {y!r}")
        self.push(y == x)
        self.move()

    def _print(self, cmd) -> "p":
        print(self.pop(), end="", flush=self.flushness)
        self.move()

    def _print_quick(self, cmd) -> "B":
        print(self.quick, end="", flush=self.flushness)
        self.move()

    def _sticky_mode_on(self, cmd) -> "k":
        self.sticky.add(self.sid)
        self.move()

    def _sticky_mode_off(self, cmd) -> "K":
        self.sticky.remove(self.sid)
        self.move()

    def _newline(self, cmd) -> "n":
        print()
        self.move()

    def _read(self, cmd) -> "r":
        self.push(input().rstrip("\n"))
        self.move()

    def _swap(self, cmd) -> "s":
        x = self.pop()
        y = self.pop()
        self.push(x)
        self.push(y)
        self.move()

    def _cast_int(self, cmd) -> "i":
        x = self.pop()
        try:
            self.push(int(x))
        except ValueError:
            raise CodeException(f"Can't cast {x!r} to int")
        self.move()

    def _cast_bool(self, cmd) -> "b":
        x = self.pop()
        try:
            self.push(bool(x))
        except ValueError:
            raise CodeException(f"Can't cast {x!r} to bool")
        self.move()

    def _cast_string(self, cmd) -> "∑":
        x = self.pop()
        try:
            self.push(str(x))
        except ValueError:
            raise CodeException(f"Can't cast {x!r} to string")
        self.move()

    def _increment(self, cmd) -> "I":
        x = self.pop()
        try:
            self.push(x + 1)
        except Exception:
            self.push(1)
        self.move()

    def _decrement(self, cmd) -> "D":
        x = self.pop()
        try:
            self.push(x - 1)
        except Exception:
            self.push(1)
        self.move()

    def _chr(self, cmd) -> "c":
        x = self.pop()
        try:
            self.push(chr(x))
        except Exception:
            self.push("\ufffd")
        self.move()

    def _ord(self, cmd) -> "o":
        x = self.pop()
        try:
            self.push(ord(x))
        except Exception:
            self.push(0)
        self.move()

    def _cast_float(self, cmd) -> "f":
        x = self.pop()
        try:
            self.push(float(x))
        except Exception:
            self.push(0)
        self.move()

    def _duplicate(self, cmd) -> "d":
        x = self.pop()
        self.push(x)
        self.push(x)
        self.move()

    def _head(self, cmd) -> "h":
        x = self.pop()
        self.stacks[self.sid] = []
        self.push(x)
        self.move()

    def _next_stack(self, cmd) -> ")":
        self.sid += 1
        self.move()

    def _prev_stack(self, cmd) -> "(":
        self.sid -= 1
        self.move()

    def _move_next_stack(self, cmd) -> "}":
        x = self.pop()
        self.sid += 1
        self.push(x)
        self.sid -= 1
        self.move()

    def _move_prev_stack(self, cmd) -> "{":
        x = self.pop()
        self.sid -= 1
        self.push(x)
        self.sid += 1
        self.move()

    def _move_go_next_stack(self, cmd) -> "]":
        x = self.pop()
        self.sid += 1
        self.push(x)
        self.move()

    def _move_go_prev_stack(self, cmd) -> "[":
        x = self.pop()
        self.sid -= 1
        self.push(x)
        self.move()

    def _negation(self, cmd) -> "!":
        self.push(not self.pop())
        self.move()

    def _die(self, cmd) -> "X":
        sys.exit()

    def _mirror_h(self, cmd) -> "|":
        cond = self.pop()
        if cond:
            new_pos = (self.x, 2**self.p - (self.y + 1))
            self.log(2, "Mirroring horizontally from", self.x, self.y, "to",
                     new_pos)
            self.move(new_pos)
        else:
            self.move()

    def _mirror_v(self, cmd) -> "_":
        cond = self.pop()
        if cond:
            new_pos = (2**self.p - (self.x + 1), self.y)
            self.log(2, "Mirroring vertically from", self.x, self.y, "to",
                     new_pos)
            self.move(new_pos)
        else:
            self.move()

    def _mirror_vh(self, cmd) -> "#":
        cond = self.pop()
        if cond:
            new_pos = (2**self.p - (self.x + 1), 2**self.p - (self.y + 1))
            self.log(2, "Mirroring (both) from", self.x, self.y, "to", new_pos)
            self.move(new_pos)
        else:
            self.move()

    def _reverse(self, cmd) -> "u":  # reverse direction
        self.dir *= -1
        self.move()

    def _reverse_stack(self, cmd) -> "U":  # reverse stack
        self.stacks[self.sid].reverse()
        self.move()

    def _string_literal(self, cmd) -> '"':
        self.mode = "string"
        self.move()

    def _char_literal(self, cmd) -> "'":
        self.mode = "char"
        self.move()

    def _escape(self, cmd) -> "\\":
        self.mode = "escape"
        self.move()

    def _cond_escape(self, cmd) -> "`":
        if not self.pop():
            self.mode = "escape"
        self.move()

    def _random_direction(self, cmd) -> "?":
        cmd_ = choice("v^<>")
        method = self.commands.get(cmd_, Aceto._nop)
        method(self, cmd)

    def _random_number(self, cmd) -> "R":
        self.push(random())
        self.move()

    def _pi(self, cmd) -> "P":
        self.push(pi)
        self.move()

    def _euler(self, cmd) -> "e":
        self.push(euler)
        self.move()

    def _invert(self, cmd) -> "~":
        x = self.pop()
        if isinstance(x, bool):
            self.push(not x)
        elif isinstance(x, Number):
            self.push(-x)
        elif isinstance(x, str):
            self.push(x[::-1])
        else:
            raise CodeException(f"Don't know how to invert {x!r}")
        self.move()

    def _bitwise_negate(self, cmd) -> "a":
        x = self.pop()
        if isinstance(x, Number):
            try:
                self.push(~x)
            except Exception:
                raise CodeException(f"Don't know how to invert {x!r}")
        else:
            y = self.pop()
            self.pushiter(reversed(re.findall(y, x)))
        self.move()

    def _restart(self, cmd) -> "O":
        if self.dir == 1:
            self.x, self.y = 0, 0
        else:
            length = 2**self.p
            self.x, self.y = 0, length - 1

    def _finalize(self, cmd) -> ";":
        if self.dir == -1:
            self.x, self.y = 0, 0
        else:
            length = 2**self.p
            self.x, self.y = 0, length - 1

    def _getch(self, cmd) -> ",":
        ch = getch()
        if ch == "\r":
            ch = ""
        self.push(ch)
        self.move()

    def _repeat(self, cmd) -> ".":
        method = self.commands.get(self.previous_cmd, Aceto._nop)
        method(self, self.previous_cmd)

    def _empty_stack(self, cmd) -> "ø":
        self.stacks[self.sid] = []
        self.move()

    def _jump(self, cmd) -> "j":
        steps = self.pop()
        distance = self.hilbert.distance_from_coordinates([self.y, self.x])
        y, x = self.hilbert.coordinates_from_distance(distance +
                                                      self.dir * steps)
        self.x, self.y = x, y

    def _goto(self, cmd) -> "§":
        distance = self.pop()
        # TODO: should take the direction (self.dir) into account.
        y, x = self.hilbert.coordinates_from_distance(distance)
        self.x, self.y = x, y

    def _join(self, cmd) -> "J":
        x, y = self.pop(), self.pop()
        self.push(str(x) + str(y))
        self.move()

    def _catch_mark(self, cmd) -> "@":
        self.catch_mark = self.x, self.y
        self.move()

    def _raise(self, cmd) -> "&":
        raise CodeException("Raised an &rror.")

    def _assert(self, cmd) -> "$":
        if self.pop():
            raise CodeException("A$$ertion failed")
        else:
            self.move()

    def _get_stopwatch(self, cmd) -> "t":
        self.push(time.time() - self.timestamp)
        self.move()

    def _set_stopwatch(self, cmd) -> "T":
        self.timestamp = time.time()
        self.move()

    def _get_datetime(self, cmd) -> "™τ":
        self.pushiter([*time.localtime()][:6][::-1])
        self.move()

    def _drop(self, cmd) -> "x":
        self.pop()
        self.move()

    def _contains(self, cmd) -> "C":
        x = self.pop()
        self.push(x in self.stacks[self.sid])
        self.move()

    def _length(self, cmd) -> "l":
        self.push(len(self.stacks[self.sid]))
        self.move()

    def _queue(self, cmd) -> "q":
        self.stacks[self.sid].insert(0, self.pop())
        self.move()

    def _unqueue(self, cmd) -> "Q":
        try:
            self.push(self.stacks[self.sid].pop(0))
        except IndexError:
            self.push(0)
        self.move()

    def _memorize_quick(self, cmd) -> "M":
        self.quick = self.pop()
        self.move()

    def _load_quick(self, cmd) -> "L":
        self.push(self.quick)
        self.move()

    def _more(self, cmd) -> "m":
        x = self.pop()
        y = self.pop()
        self.log(2, f"Testing if {y!r} > {x!r}")
        self.push(y > x)
        self.move()

    def _less_or_equal(self, cmd) -> "w":
        x = self.pop()
        y = self.pop()
        self.log(2, f"Testing if {y!r} <= {x!r}")
        self.push(y <= x)
        self.move()

    def _bitwise_and(self, cmd) -> "A":
        x = self.pop()
        y = self.pop()
        self.push(y & x)
        self.move()

    def _bitwise_or(self, cmd) -> "V":
        x = self.pop()
        y = self.pop()
        self.push(y | x)
        self.move()

    def _bitwise_xor(self, cmd) -> "H":
        x = self.pop()
        y = self.pop()
        self.push(y ^ x)
        self.move()

    def _range_down(self, cmd) -> "z":
        val = self.pop()
        if not isinstance(val, int) or val == 0:
            raise CodeException("Can only construct range with non-0 integer")
        step = -1 if val > 0 else 1
        self.pushiter(range(val, 0, step))
        self.move()

    def _range_up(self, cmd) -> "Z":
        val = self.pop()
        if not isinstance(val, int) or val == 0:
            raise CodeException("Can only construct range with non-0 integer")
        step = 1 if val > 0 else -1
        self.pushiter(range(step, val + step, step))
        self.move()

    def _order_up(self, cmd) -> "G":
        x = [self.pop(), self.pop()]
        x.sort()
        self.push(x.pop())
        self.push(x.pop())
        self.move()

    def _order_down(self, cmd) -> "g":
        x = [self.pop(), self.pop()]
        x.sort(reverse=True)
        self.push(x.pop())
        self.push(x.pop())
        self.move()

    def _shuffle(self, cmd) -> "Y":
        shuffle(self.stacks[self.sid])
        self.move()

    def _sign(self, cmd) -> "y":
        x = self.pop()
        self.push(1 if x > 0 else -1 if x < 0 else 0)
        self.move()

    def _bitwise_left(self, cmd) -> "«":
        x = self.pop()
        y = self.pop()
        self.push(y << x)
        self.move()

    def _bitwise_right(self, cmd) -> "»":
        x = self.pop()
        y = self.pop()
        self.push(y >> x)
        self.move()

    def _multiply_stack(self, cmd) -> "×":
        x = self.pop()
        self.stacks[self.sid] *= x
        self.move()

    def _abs(self, cmd) -> "±":
        x = self.pop()
        self.push(abs(x))
        self.move()

    def _explode_string(self, cmd) -> "€":
        x = self.pop()
        self.stacks[self.sid].extend(reversed(x))
        self.move()

    def _implode_string(self, cmd) -> "£¥":
        s = "".join(map(str, reversed(self.stacks[self.sid])))
        self.stacks[self.sid] = [s]
        self.move()
Пример #26
0
def main():
    """
    calculates a hilbert pseudocurve of p iterations.
    Scale the pseudocurve to match the desired image.
    Move along the curve and sample image and to get average color at each segment
    Output gcode corresponding the coordinates and scaled Z levels.

    If no image is given, a flat hilbert curve of the desired size is produced.
    """

    parser = argparse.ArgumentParser(description='Generate a hilbert curve')

    parser.add_argument(
        '-p',
        '--iterations',
        type=int,
        default=5,
        help='hilbert curve is fractal, number of iterative levels')
    parser.add_argument('-s',
                        '--size',
                        type=int,
                        default=100,
                        help='size in millimeters')
    parser.add_argument('-zmin',
                        type=float,
                        default=0,
                        help='The minimum z value which approximates black')
    parser.add_argument('-zmax',
                        type=float,
                        default=255,
                        help='The maximum z value which approximates white')
    parser.add_argument(
        '--laser',
        action='store_true',
        help='Z values will be output as spindle power (S words)')
    parser.add_argument('-F',
                        '--FEED',
                        type=int,
                        default=4000,
                        help='Feed rate in mm/min, default = 4000')
    parser.add_argument('-i', '--infile', help='image filename to process')
    parser.add_argument('-o', '--outfile', help='gcode filename to write')

    args = parser.parse_args()

    N = 2  # Number of dimensions.  For images, this is always 2
    MAX = 2**(args.iterations * N) - 1
    scalefactor = args.size / (math.sqrt(MAX + 1))

    imagefile = None

    if args.infile is not None:
        imagefile = Image.open(args.infile)

        if imagefile.size[0] != imagefile.size[1]:
            print('the image is not square. It will be cropped')
            cropsize = min(imagefile.size)
            imagefile = imagefile.crop((0, 0, cropsize, cropsize))
        imagefactor = imagefile.size[0] / (math.sqrt(MAX + 1))

    hilbert_curve = HilbertCurve(args.iterations, N)
    with open(args.outfile, "w") as outfile:
        outfile.write(PREAMBLE)
        for ii in range(MAX):
            coords = hilbert_curve.coordinates_from_distance(ii)

            if imagefile is not None:
                zval = get_average_color(x=int(coords[0] * imagefactor),
                                         y=int(coords[1] * imagefactor),
                                         n=5,
                                         img=imagefile)
            else:
                zval = 1
            scalez = (args.zmax - args.zmin) / 255 * zval - 0 + args.zmin

            if args.laser:
                #outfile.write(f'M3 S{scalez}\n')
                outfile.write(
                    f'G1 X{coords[0]*scalefactor} Y{coords[1]*scalefactor} F{scalez}\n'
                )
            else:
                outfile.write(
                    f'G1 X{coords[0]*scalefactor} Y{coords[1]*scalefactor} Z{scalez} F{args.FEED}\n'
                )

        outfile.write(POSTAMBLE)
Пример #27
0
class LibMyPaintInterface:

    def __init__(self, episode_length, color_type="rgb", coord_type="cart", grid_size=32, canvas_size=64, background="white"):
        self.grid_size = grid_size  # size of the action grid
        self.episode_length = 2 * episode_length  # nombre d'action à prédire pour chaque episode

        env_settings = dict(
            episode_length=self.episode_length + 1,  # Number of frames in each episode.
            canvas_width=canvas_size,  # The width of the canvas in pixels.
            grid_width=self.grid_size,  # The width of the action grid.
            brushes_basedir="third_party/libmypaint_brushes/",  # The location of libmypaint brushes.
            brush_type="classic/dry_brush",  # The type of the brush.
            brush_sizes=[1, 2, 4, 8, 16],  # The sizes of the brush to use.
            use_color=color_type != "grey",  # Color or black & white output?
            use_pressure=True,  # Use pressure parameter of the brush?
            use_alpha=False,  # Drop or keep the alpha channel of the canvas?
            background=background  # Background could either be "white" or "transparent".
        )

        self.color_type = color_type
        if (color_type == "rgb") or (color_type == "grey"):
            self.env = LibMyPaint(**env_settings)
            self.color_name = ["red", "green", "blue"]
        elif color_type == "hsv":
            self.env = LibMyPaint_hsv(**env_settings)
            self.color_name = ["hue", "saturation", "value"]
        else:
            raise ValueError("color_type must be 'grey', 'rgb' or 'hsv'")

        self.observation_space = ObservationSpace(self.env.observation_spec())
        self.action_space = ActionSpace(shape=11)
        self.max_norm = self._distance_l2(np.ones(self.observation_space.shape), np.zeros(self.observation_space.shape))

        self.coord_type = coord_type
        if (coord_type != "cart" and
                coord_type != "hilb"):
            raise ValueError("coord_type must be 'cart' or 'hilb'")
        elif coord_type == "hilb":
            l = m.log(self.grid_size, 2)
            assert l - int(l) == 0, "the action grid size can't be converted to an hilbert curve"
            self.hilbert_curve = HilbertCurve(p=int(l), n=2)
            self.action_space = ActionSpace(shape=8)

        self.state = self.env.reset()
        self.target = None

        self.actions = []  # TODO

    @staticmethod
    def _map_to_int_interval(to_map, start, end):
        i = start + to_map * (end - start)
        return int(round(i))

    @staticmethod
    def _distance_l2(matrix1, matrix2):
        return np.linalg.norm(matrix1 - matrix2)

    def reset(self, target):
        """
        Reinitializes the reinforcement learning environment
        
        Takes as inputs
        - target : 3d numpy array of shape (height, width, channels) values must be in [0,1]
        Returns
        - observable : 3d numpy array of shape (height, width, channels) representing the new state of the environment
        """
        self.state = self.env.reset()
        self.actions = []
        self.target = target

        return self.getObservable()

    def getObservable(self):
        """
        Returns the observable data of the environment

        Returns
        - observable :  the current target and
                        3d numpy array of shape (height, width, channels) representing the new state of the environment
        """
        assert self.target is not None, "The target not define, to do so reset the environment"

        return np.array([self.target,
                         self.state.observation["canvas"]])

    def step(self, action):
        """
        Updates the environment with the given action
        
        Takes as inputs
        - action : array of value € [0,1] representing an action
        Returns
        - observable : 3d numpy array of shape (height, width, channels) representing the new state of the environment
        - reward : reward given to the agent for the performed action
        - done : boolean indicating if new state is a terminal state
        - infos : dictionary of informations (for debugging purpose)
        """

        assert self.target is not None, "The target not define, to do so reset the environment"

        if self.state.step_type == environment.StepType.LAST:
            return (self.getObservable(),
                    1 / ((LibMyPaintInterface._distance_l2(self.state.observation["canvas"], self.target) + 1e-9) / self.max_norm),
                    True,
                    {"info": "To continue reset the environment"})

        self.actions.append(action)

        action_spec = self.env.action_spec()

        # extract the values
        if self.coord_type == "cart":
            x_start, y_start, x_control, y_control, x_end, y_end, brush_pressure, brush_size, color_1, color_2, color_3 = action
            # map the coordinates to the right interval
            x_start = LibMyPaintInterface._map_to_int_interval(x_start, 0, self.grid_size - 1)
            y_start = LibMyPaintInterface._map_to_int_interval(y_start, 0, self.grid_size - 1)
            x_control = LibMyPaintInterface._map_to_int_interval(x_control, 0, self.grid_size - 1)
            y_control = LibMyPaintInterface._map_to_int_interval(y_control, 0, self.grid_size - 1)
            x_end = LibMyPaintInterface._map_to_int_interval(x_end, 0, self.grid_size - 1)
            y_end = LibMyPaintInterface._map_to_int_interval(y_end, 0, self.grid_size - 1)

        elif self.coord_type == "hilb":
            start, control, end, brush_pressure, brush_size, color_1, color_2, color_3 = action
            # map the coordonates to the right interval
            start = int(LibMyPaintInterface._map_to_int_interval(start, 0, pow(2, m.log(self.grid_size, 2) * 2) - 1))
            control = int(LibMyPaintInterface._map_to_int_interval(control, 0, pow(2, m.log(self.grid_size, 2) * 2) - 1))
            end = int(LibMyPaintInterface._map_to_int_interval(end, 0, pow(2, m.log(self.grid_size, 2) * 2) - 1))
            x_start, y_start = self.hilbert_curve.coordinates_from_distance(start)
            x_control, y_control = self.hilbert_curve.coordinates_from_distance(control)
            x_end, y_end = self.hilbert_curve.coordinates_from_distance(end)

        brush_pressure = LibMyPaintInterface._map_to_int_interval(brush_pressure,
                                                                  action_spec["pressure"].minimum,
                                                                  action_spec["pressure"].maximum)

        brush_size = LibMyPaintInterface._map_to_int_interval(brush_size,
                                                              action_spec["size"].minimum,
                                                              action_spec["size"].maximum)

        color_1 = LibMyPaintInterface._map_to_int_interval(color_1,
                                                           action_spec[self.color_name[0]].minimum,
                                                           action_spec[self.color_name[1]].maximum)

        color_2 = LibMyPaintInterface._map_to_int_interval(color_2,
                                                           action_spec[self.color_name[1]].minimum,
                                                           action_spec[self.color_name[1]].maximum)

        color_3 = LibMyPaintInterface._map_to_int_interval(color_3,
                                                           action_spec[self.color_name[2]].minimum,
                                                           action_spec[self.color_name[2]].maximum)

        # go to the start of the curve
        move = {"control": np.ravel_multi_index((x_start, y_start),
                                                (self.grid_size, self.grid_size)).astype("int32"),
                "end": np.ravel_multi_index((x_start, y_start),
                                            (self.grid_size, self.grid_size)).astype("int32"),
                "flag": np.int32(0),
                "pressure": np.int32(brush_pressure),
                "size": np.int32(brush_size),
                self.color_name[0]: np.int32(color_1),
                self.color_name[1]: np.int32(color_2),
                self.color_name[2]: np.int32(color_3)}
        self.state = self.env.step(move)

        if self.state.step_type == environment.StepType.LAST:
            return (self.getObservable(),
                    1 / ((LibMyPaintInterface._distance_l2(self.state.observation["canvas"], self.target) + 1e-9) / self.max_norm),
                    True,
                    {})

        # draw the curve
        draw = {"control": np.ravel_multi_index((x_control, y_control),
                                                (self.grid_size, self.grid_size)).astype("int32"),
                "end": np.ravel_multi_index((x_end, y_end),
                                            (self.grid_size, self.grid_size)).astype("int32"),
                "flag": np.int32(1),
                "pressure": np.int32(brush_pressure),
                "size": np.int32(brush_size),
                self.color_name[0]: np.int32(color_1),
                self.color_name[1]: np.int32(color_2),
                self.color_name[2]: np.int32(color_3)}
        self.state = self.env.step(draw)

        if self.state.step_type == environment.StepType.LAST:
            return (self.getObservable(),
                    1 / ((LibMyPaintInterface._distance_l2(self.state.observation["canvas"], self.target) + 1e-9) / self.max_norm),
                    True,
                    {})

        return (self.getObservable(),
                0,
                False,
                {})

    def close(self):
        self.env.close()

    def render(self, modes=None):
        """
        Returns a graphic representation of the environment
        
        Takes as inputs
        - mode : ø
        Returns
        - a render of the environment state, given in the requested mode
        """
        img = self.getObservable()[1]
        if self.color_type == "hsv":
            img = np.array([[cs.hsv_to_rgb(img[i, j][0],
                                           img[i, j][1],
                                           img[i, j][2]) for j in range(64)] for i in range(64)])
        if modes:
            if isinstance(modes, list) or isinstance(modes, tuple):
                if "display" in modes:
                    plt.imshow(img * 255)
                    plt.show()
            else:
                if modes == "display":
                    plt.imshow(img * 255)
                    plt.show()
        return (img * 255).astype("uint8")
url_map, p = map_all_urls(all_urls, N)
hilbert_curve = HilbertCurve(p, N)

# %%
# iterate over all results
x = y = c = d = []
for day, file in enumerate(files[:5]):
    # import dataset
    kwMetadata = pd.read_pickle(file)
    # get full url
    # kwMetadata["urls"] = kwMetadata["result_hash"].apply(lambda x: get_full_url(hashmap[x]))
    #get hilbert curve for day
    curve = np.zeros(((len(kwMetadata) * 10, 4)))
    for idx in range(len(kwMetadata)):
        for jdx in range(10):
            x, y = hilbert_curve.coordinates_from_distance(
                url_map[kwMetadata.urls[idx][jdx]])
            curve[idx * 10 + jdx, 0] = x
            curve[idx * 10 + jdx, 1] = y
            curve[idx * 10 + jdx, 2] = kwMetadata.cluster[idx]
            curve[idx * 10 + jdx, 3] = day
    x_day, y_day, c_day, day = curve
    x.append(x_day)
    y.append(y_day)
    c.append(c_day)
    d.append(day)

# %% get ALL urls from all datasets
datasets = []
for file in os.listdir(os.path.join('Datasets')):
    if file.endswith(".json"):
        datasets.append(file)
Пример #29
0
import numpy as np
from hilbertcurve.hilbertcurve import HilbertCurve
import matplotlib.pyplot as plt

R = 0.1
spacing = 1.75 * R
velocity = 0.1
dt = 0.05

Simulation = mr_sim.create_simulation(mr_sim.Round, mr_sim.Flat, mr_sim.Rotary,
                                      mr_sim.Preston)

curve = HilbertCurve(3, 2)

points = np.array(
    [curve.coordinates_from_distance(d) for d in range(curve.max_h + 1)],
    np.float)
points -= curve.max_x / 2
points *= spacing

t_final = curve.max_h * spacing / velocity
point_times = np.linspace(0, t_final, points.shape[0])
t = np.arange(0, t_final, dt)

path = np.vstack(
    (np.interp(t, point_times,
               points[:, 0]), np.interp(t, point_times, points[:, 1]))).T

size = spacing * curve.max_x + 2 * R

simulation = Simulation(size,
        for greenpixel_value in pixel_greenchannel_array:
            greenchannel_sum = greenchannel_sum + greenpixel_value
        pixelgreenchannel_avg = greenchannel_sum/len(pixel_greenchannel_array)
        for bluepixel_value in pixel_bluechannel_array:
            bluechannel_sum = bluechannel_sum + bluepixel_value
        pixelbluechannel_avg = bluechannel_sum/len(pixel_bluechannel_array)

        if round(pixelredchannel_avg *256) > 256:
            pixelredchannel_avg = 256
        if round(pixelgreenchannel_avg *256) > 256:
            pixelgreenchannel_avg = 256
        if round(pixelbluechannel_avg *256) > 256:
            pixelbluechannel_avg = 256


        coords = curve.coordinates_from_distance(pixelcounter)
        # print(f'coords(h={pixelcounter}) = {coords}')
        img.putpixel((coords[0],coords[1]), (round(pixelredchannel_avg *256), round(pixelgreenchannel_avg*256), round(pixelbluechannel_avg*256)))


    if pixelcounter+movingwindowparameter + 5 < max_hilbert_length:
        pixelcounter = pixelcounter + 1
        pixelXposition = pixelXposition+1
    else:
        break


img.save('DNAimage.png')
    
# # pixels = new.load()
# #print("The length of the DNA file is: " + str(sequencelength))