text:
"""
This is borrowed from FudanParser. Not stable. Do not use !!!

"""
import numpy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from torch import optim
from torch.autograd import Function, Variable
from torch.nn import Parameter

from .utils import orthogonal

class GroupNorm(nn.Module):
    def __init__(self, num_features, num_groups=20, eps=1e-5):
        super(GroupNorm, self).__init__()
        self.weight = nn.Parameter(torch.ones(1, num_features, 1))
        self.bias = nn.Parameter(torch.zeros(1, num_features, 1))
        self.num_groups = num_groups
        self.eps = eps

    def forward(self, x):
        N, C, H = x.size()
        G = self.num_groups
        assert C % G == 0

        x = x.view(N, G, -1)
        mean = x.mean(-1, keepdim=True)
        var = x.var(-1, keepdim=True)

        x = (x - mean) / (var + self.eps).sqrt()
        x = x.view(N, C, H)
        return x * self.weight + self.bias

class LayerNormalization(nn.Module):
    """ Layer normalization module """

    def __init__(self, d_hid, eps=1e-3):
        super(LayerNormalization, self).__init__()

        self.eps = eps
        self.a_2 = nn.Parameter(torch.ones(d_hid), requires_grad=True)
        self.b_2 = nn.Parameter(torch.zeros(d_hid), requires_grad=True)

    def forward(self, z):
        if z.size(1) == 1:
            return z

        mu = torch.mean(z, keepdim=True, dim=-1)
        sigma = torch.std(z, keepdim=True, dim=-1)
        ln_out = (z - mu.expand_as(z)) / (sigma.expand_as(z) + self.eps)
        ln_out = ln_out * self.a_2.expand_as(ln_out) + self.b_2.expand_as(ln_out)

        return ln_out

class OrthEmbedding(nn.Embedding):
    def __init__(self, *args, **kwargs):
        super(OrthEmbedding, self).__init__(*args, **kwargs)

    def reset_parameters(self):
        self.weight = orthogonal(self.weight)
        nn.init.constant_(self.bias, 0.)

class BiLinear(nn.Module):
    def __init__(self, n_left, n_right, n_out, bias=True):
        """
        Args:
            n_left: size of left input
            n_right: size of right input
            n_out: size of output
            bias: If set to False, the layer will not learn an additive bias.
                Default: True
        """
        super(BiLinear, self).__init__()
        self.n_left = n_left
        self.n_right = n_right
        self.n_out = n_out

        self.U = Parameter(torch.Tensor(self.n_out, self.n_left, self.n_right))
        self.W_l = Parameter(torch.Tensor(self.n_out, self.n_left))
        self.W_r = Parameter(torch.Tensor(self.n_out, self.n_left))

        if bias:
            self.bias = Parameter(torch.Tensor(n_out))
        else:
            self.register_parameter('bias', None)

        self.reset_parameters()

    def reset_parameters(self):
        nn.init.xavier_uniform_(self.W_l)
        nn.init.xavier_uniform_(self.W_r)
        nn.init.constant_(self.bias, 0.)
        nn.init.xavier_uniform_(self.U)

    def forward(self, input_left, input_right):
        """
        Args:
            input_left: Tensor
                the left input tensor with shape = [batch1, batch2, ..., left_features]
            input_right: Tensor
                the right input tensor with shape = [batch1, batch2, ..., right_features]
        Returns:
        """
        left_size = input_left.size()
        right_size = input_right.size()
        assert left_size[:-1] == right_size[:-1], \
            "batch size of left and right inputs mis-match: (%s, %s)" % (left_size[:-1], right_size[:-1])
        batch = int(np.prod(left_size[:-1]))

        # convert left and right input to matrices [batch, left_features], [batch, right_features]
        input_left = input_left.view(batch, self.n_left)
        input_right = input_right.view(batch, self.n_right)

        # output [batch, out_features]
        output = F.bilinear(input_left, input_right, self.U, self.bias)
        output = output + \
                 F.linear(input_left, self.W_l, None) + \
                 F.linear(input_right, self.W_r, None)
        # convert back to [batch1, batch2, ..., out_features]
        return output.view(left_size[:-1] + (self.n_out,))

    def __repr__(self):
        return self.__class__.__name__ + ' (' \
               + 'in1_features=' + str(self.n_left) \
               + ', in2_features=' + str(self.n_right) \
               + ', out_features=' + str(self.n_out) + ')'

class BiAffine(nn.Module):
    def __init__(self, n_enc, n_dec, n_labels, biaffine=True, **kwargs):
        """
        Args:
            n_enc: int
                the dimension of the encoder input.
            n_dec: int
                the dimension of the decoder input.
            n_labels: int
                the number of labels of the crf layer
            biaffine: bool
                if apply bi-affine parameter.
            **kwargs:
        """
        super(BiAffine, self).__init__()
        self.n_enc = n_enc
        self.n_dec = n_dec
        self.num_labels = n_labels
        self.biaffine = biaffine

        self.W_d = Parameter(torch.Tensor(self.num_labels, self.n_dec))
        self.W_e = Parameter(torch.Tensor(self.num_labels, self.n_enc))
        self.b = Parameter(torch.Tensor(self.num_labels, 1, 1))
        if self.biaffine:
            self.U = Parameter(torch.Tensor(self.num_labels, self.n_dec, self.n_enc))
        else:
            self.register_parameter('U', None)

        self.reset_parameters()

    def reset_parameters(self):
        nn.init.xavier_uniform_(self.W_d)
        nn.init.xavier_uniform_(self.W_e)
        nn.init.constant_(self.b, 0.)
        if self.biaffine:
            nn.init.xavier_uniform_(self.U)

    def forward(self, input_d, input_e, mask_d=None, mask_e=None):
        """
        Args:
            input_d: Tensor
                the decoder input tensor with shape = [batch, length_decoder, input_size]
            input_e: Tensor
                the child input tensor with shape = [batch, length_encoder, input_size]
            mask_d: Tensor or None
                the mask tensor for decoder with shape = [batch, length_decoder]
            mask_e: Tensor or None
                the mask tensor for encoder with shape = [batch, length_encoder]
        Returns: Tensor
            the energy tensor with shape = [batch, num_label, length, length]
        """
        assert input_d.size(0) == input_e.size(0), 'batch sizes of encoder and decoder are requires to be equal.'
        batch, length_decoder, _ = input_d.size()
        _, length_encoder, _ = input_e.size()

        # compute decoder part: [num_label, input_size_decoder] * [batch, input_size_decoder, length_decoder]
        # the output shape is [batch, num_label, length_decoder]
        out_d = torch.matmul(self.W_d, input_d.transpose(1, 2)).unsqueeze(3)
        # compute decoder part: [num_label, input_size_encoder] * [batch, input_size_encoder, length_encoder]
        # the output shape is [batch, num_label, length_encoder]
        out_e = torch.matmul(self.W_e, input_e.transpose(1, 2)).unsqueeze(2)

        # output shape [batch, num_label, length_decoder, length_encoder]
        if self.biaffine:
            # compute bi-affine part
            # [batch, 1, length_decoder, input_size_decoder] * [num_labels, input_size_decoder, input_size_encoder]
            # output shape [batch, num_label, length_decoder, input_size_encoder]
            output = torch.matmul(input_d.unsqueeze(1), self.U)
            # [batch, num_label, length_decoder, input_size_encoder] * [batch, 1, input_size_encoder, length_encoder]
            # output shape [batch, num_label, length_decoder, length_encoder]
            output = torch.matmul(output, input_e.unsqueeze(1).transpose(2, 3))

            output = output + out_d + out_e + self.b
        else:
            output = out_d + out_d + self.b

        if mask_d is not None:
            output = output * mask_d.unsqueeze(1).unsqueeze(3) * mask_e.unsqueeze(1).unsqueeze(2)

        return output

class Transpose(nn.Module):
    def __init__(self, x, y):
        super(Transpose, self).__init__()
        self.x = x
        self.y = y

    def forward(self, x):
        return x.transpose(self.x, self.y)

class WordDropout(nn.Module):
    def __init__(self, dropout_rate, drop_to_token):
        super(WordDropout, self).__init__()
        self.dropout_rate = dropout_rate
        self.drop_to_token = drop_to_token

    def forward(self, word_idx):
        if not self.training:
            return word_idx
        drop_mask = torch.rand(word_idx.shape) < self.dropout_rate
        if word_idx.device.type == 'cuda':
            drop_mask = drop_mask.cuda()
        drop_mask = drop_mask.long()
        output = drop_mask * self.drop_to_token + (1 - drop_mask) * word_idx
        return output

class WlossLayer(torch.nn.Module):
    def __init__(self, lam=100, sinkhorn_iter=50):
        super(WlossLayer, self).__init__()

        # cost = matrix M = distance matrix
        # lam = lambda of type float > 0
        # sinkhorn_iter > 0
        # diagonal cost should be 0
        self.lam = lam
        self.sinkhorn_iter = sinkhorn_iter
        # self.register_buffer("K", torch.exp(-self.cost / self.lam).double())
        # self.register_buffer("KM", (self.cost * self.K).double())

    def forward(self, pred, target, cost):
        return WassersteinLossStab.apply(pred, target,
                                         cost, self.lam, self.sinkhorn_iter)

class WassersteinLossStab(Function):
    @staticmethod
    def forward(ctx, pred, target, cost, lam=1e-3, sinkhorn_iter=4):
        """pred: Batch * K: K = # mass points
           target: Batch * L: L = # mass points"""
        # import pdb
        # pdb.set_trace()
        eps = 1e-8

        # pred = pred.gather(dim=1, index=)
        na = pred.size(1)
        nb = target.size(1)

        cost = cost.double()
        pred = pred.double()
        target = target.double()

        cost = cost[:na, :nb].double()
        K = torch.exp(-cost / lam).double()
        KM = (cost * K).double()

        batch_size = pred.size(0)

        # pdb.set_trace()
        log_a, log_b = torch.log(pred + eps), torch.log(target + eps)
        log_u = cost.new(batch_size, na).fill_(-numpy.log(na))
        log_v = cost.new(batch_size, nb).fill_(-numpy.log(nb))
        # import pdb
        # pdb.set_trace()
        for i in range(int(sinkhorn_iter)):
            log_u_max = torch.max(log_u, dim=1)[0]
            u_stab = torch.exp(log_u - log_u_max.unsqueeze(1) + eps)
            log_v = log_b - torch.log(torch.mm(K.t(), u_stab.t()).t()) - log_u_max.unsqueeze(1)
            log_v_max = torch.max(log_v, dim=1)[0]
            v_stab = torch.exp(log_v - log_v_max.unsqueeze(1))
            tmp = log_u
            log_u = log_a - torch.log(torch.mm(K, v_stab.t()).t() + eps) - log_v_max.unsqueeze(1)
            # print(log_u.sum())
            if torch.norm(tmp - log_u) / torch.norm(log_u) < eps:
                break

        log_v_max = torch.max(log_v, dim=1)[0]
        v_stab = torch.exp(log_v - log_v_max.unsqueeze(1))
        logcostpart1 = torch.log(torch.mm(KM, v_stab.t()).t() + eps) + log_v_max.unsqueeze(1)
        wnorm = torch.exp(log_u + logcostpart1).mean(0).sum()  # sum(1) for per item pair loss...
        grad_input = log_u * lam
        # print("log_u", log_u)
        grad_input = grad_input - torch.mean(grad_input, dim=1).unsqueeze(1)
        grad_input = grad_input - torch.mean(grad_input, dim=1).unsqueeze(1)
        grad_input = grad_input / batch_size

        ctx.save_for_backward(grad_input)
        # print("grad type", type(grad_input))

        return pred.new((wnorm,)), grad_input

    @staticmethod
    def backward(ctx, grad_output, _):
        grad_input = ctx.saved_variables
        # print(grad)
        res = grad_output.clone()
        res.data.resize_(grad_input[0].size()).copy_(grad_input[0].data)
        res = res.mul_(grad_output[0]).float()
        # print("in backward func:\n\n", res)
        return res, None, None, None, None, None, None

class Sinkhorn(Function):
    def __init__(self):
        super(Sinkhorn, self).__init__()

    def forward(ctx, a, b, M, reg, tau, warmstart, numItermax, stop):
        a = a.double()
        b = b.double()
        M = M.double()

        nbb = b.size(1)

        # init data
        na = len(a)
        nb = len(b)

        cpt = 0

        # we assume that no distances are null except those of the diagonal of
        # distances
        if warmstart is None:
            alpha, beta = np.zeros(na), np.zeros(nb)
        else:
            alpha, beta = warmstart

        if nbb:
            u, v = np.ones((na, nbb)) / na, np.ones((nb, nbb)) / nb
        else:
            u, v = np.ones(na) / na, np.ones(nb) / nb

        def get_K(alpha, beta):
            """log space computation"""
            return np.exp(-(M - alpha.reshape((na, 1)) - beta.reshape((1, nb))) / reg)

        def get_Gamma(alpha, beta, u, v):
            """log space gamma computation"""
            return np.exp(
                -(M - alpha.reshape((na, 1)) - beta.reshape((1, nb))) / reg + np.log(u.reshape((na, 1))) + np.log(
                    v.reshape((1, nb))))

        # print(np.min(K))

        K = get_K(alpha, beta)
        transp = K
        cpt = 0
        err = 1
        while 1:

            uprev = u
            vprev = v

            # sinkhorn update
            v = b / (np.dot(K.T, u) + 1e-16)
            u = a / (np.dot(K, v) + 1e-16)

            # remove numerical problems and store them in K
            if np.abs(u).max() > tau or np.abs(v).max() > tau:
                if nbb:
                    alpha, beta = alpha + reg * \
                                  np.max(np.log(u), 1), beta + reg * np.max(np.log(v))
                else:
                    alpha, beta = alpha + reg * np.log(u), beta + reg * np.log(v)
                    if nbb:
                        u, v = np.ones((na, nbb)) / na, np.ones((nb, nbb)) / nb
                    else:
                        u, v = np.ones(na) / na, np.ones(nb) / nb
                K = get_K(alpha, beta)

            if cpt % print_period == 0:
                # we can speed up the process by checking for the error only all
                # the 10th iterations
                if nbb:
                    err = np.sum((u - uprev) ** 2) / np.sum((u) ** 2) + \
                          np.sum((v - vprev) ** 2) / np.sum((v) ** 2)
                else:
                    transp = get_Gamma(alpha, beta, u, v)
                    err = np.linalg.norm((np.sum(transp, axis=0) - b)) ** 2
                if log:
                    log['err'].append(err)

                if verbose:
                    if cpt % (print_period * 20) == 0:
                        print(
                            '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
                    print('{:5d}|{:8e}|'.format(cpt, err))

            if err <= stopThr:
                loop = False

            if cpt >= numItermax:
                loop = False

            if np.any(np.isnan(u)) or np.any(np.isnan(v)):
                # we have reached the machine precision
                # come back to previous solution and quit loop
                print('Warning: numerical errors at iteration', cpt)
                u = uprev
                v = vprev
                break

            cpt = cpt + 1

        # print('err=',err,' cpt=',cpt)
        if log:
            log['logu'] = alpha / reg + np.log(u)
            log['logv'] = beta / reg + np.log(v)
            log['alpha'] = alpha + reg * np.log(u)
            log['beta'] = beta + reg * np.log(v)
            log['warmstart'] = (log['alpha'], log['beta'])
            if nbb:
                res = np.zeros((nbb))
                for i in range(nbb):
                    res[i] = np.sum(get_Gamma(alpha, beta, u[:, i], v[:, i]) * M)
                return res, log

            else:
                return get_Gamma(alpha, beta, u, v), log
        else:
            if nbb:
                res = np.zeros((nbb))
                for i in range(nbb):
                    res[i] = np.sum(get_Gamma(alpha, beta, u[:, i], v[:, i]) * M)
                return res
            else:
                return get_Gamma(alpha, beta, u, v)

if __name__ == "__main__":
    cost = (torch.Tensor(2, 2).fill_(1) - torch.diag(torch.Tensor(2).fill_(1)))  # .cuda()
    mylayer = WlossLayer(cost)  # .cuda()
    inp = Variable(torch.Tensor([[1, 0], [0.5, 0.5]]), requires_grad=True)  # .cuda()
    ground_true = Variable(torch.Tensor([[0, 1], [0.5, 0.5]]))  # .cuda()

    res, _ = mylayer(inp, ground_true)
    # print(inp.requires_grad, res.requires_grad)
    # print(res, inp)
    mylayer.zero_grad()
    res.backward()
    print("inp's gradient is good:")
    print(inp.grad)

    print("convert to gpu:\n", inp.cuda().grad)
    print("=============================================="
          "\n However, this does not work on pytorch when GPU is enabled")

    cost = (torch.Tensor(2, 2).fill_(1) - torch.diag(torch.Tensor(2).fill_(1))).cuda()
    mylayer = WlossLayer(cost).cuda()
    inp = Variable(torch.Tensor([[1, 0], [0.5, 0.5]]), requires_grad=True).cuda()
    ground_true = Variable(torch.Tensor([[0, 1], [0.5, 0.5]])).cuda()

    opt = optim.SGD([
        {'params': mylayer.parameters()},
    ], lr=1e-2, momentum=0.9)

    res, _ = mylayer(inp, ground_true)
    # print(inp.requires_grad, res.requires_grad)
    # print(res, inp)
    mylayer.zero_grad()
    res.backward()
    print("input's gradient is None!!!!!!!!!!!!!!!!")
    print(inp.grad)


text:
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *

from bw2calc import *
from bw2data import Database, Method, mapping
from bw2data.tests import bw2test
import numpy as np
import pytest

def build_databases():
    Database("biosphere").write({
        ("biosphere", "1"): {'type': 'emission'},
        ("biosphere", "2"): {'type': 'emission'},
    })
    Database("test").write({
        ("test", "1"): {
            'exchanges': [{
                'amount': 0.5,
                'minimum': 0.2,
                'maximum': 0.8,
                'input': ('test', "2"),
                'type': 'technosphere',
                'uncertainty type': 4  # Uniform
            }, {
                'amount': 100,
                'minimum': 50,
                'maximum': 500,
                'input': ('biosphere', "1"),
                'type': 'biosphere',
                'loc': 100,
                'scale': 20,
                'uncertainty type': 3  # Normal
            }],
            'type': 'process',
        },
        ("test", "2"): {
            'exchanges': [{
                'amount': -0.42,
                'input': ('biosphere', "2"),
                'type': 'biosphere',
            }],
            'type': 'process',
            'unit': 'kg'
        },
    })
    method = Method(("a", "method"))
    method.register()
    method.write([
        (("biosphere", "1"), 1),
        (("biosphere", "2"), {
            'amount': 10,
            'uncertainty type': 5,  # Triangular
            'loc': 10,
            'minimum': 8,
            'maximum': 15
        }),
    ])

@pytest.fixture
@bw2test
def background():
    build_databases()

def test_pv_no_need_load_data(background):
    assert next(ParameterVectorLCA({("test", "1"): 1}, ("a", "method")))

def test_pv_ordering_correct(background):
    pv = ParameterVectorLCA({("test", "1"): 1}, ("a", "method"))
    pv.load_data()

    b1 = pv.biosphere_dict[("biosphere", "1")]
    b2 = pv.biosphere_dict[("biosphere", "2")]
    p1 = pv.product_dict[("test", "1")]
    p2 = pv.product_dict[("test", "2")]
    a1 = pv.activity_dict[("test", "1")]
    a2 = pv.activity_dict[("test", "2")]

    for _ in range(10):
        next(pv)
        assert pv.characterization_matrix[b1, b1] == 1
        assert 8 <= pv.characterization_matrix[b2, b2] <= 15
        assert pv.characterization_matrix[b2, b1] == 0

        assert np.allclose(pv.biosphere_matrix[b2, a2], -0.42)
        assert pv.biosphere_matrix[b1, a1] >= 50

        assert pv.technosphere_matrix[p1, a1] == 1
        assert pv.technosphere_matrix[p2, a2] == 1
        assert pv.technosphere_matrix[p1, a2] == 0
        # Inputs are negative
        assert -0.8 <= pv.technosphere_matrix[p2, a1] <= -0.2

        assert 8 <= pv.characterization_matrix[b2, b2] <= 15
        assert pv.characterization_matrix[b2, b1] == 0

def test_raise_assertion_error_with_wrong_size_vector(background):
    pv = ParameterVectorLCA({("test", "1"): 1}, ("a", "method"))
    with pytest.raises(AssertionError):
        pv.rebuild_all(np.ones(100,))

def test_no_error_with_right_size_vector(background):
    pv = ParameterVectorLCA({("test", "1"): 1}, ("a", "method"))
    pv.rebuild_all(np.ones(7,))

def test_stored_samples_correct(background):
    pv = ParameterVectorLCA({("test", "1"): 1}, ("a", "method"))
    pv.load_data()

    samples = []
    for x in range(10):
        next(pv)
        samples.append(pv.sample.copy())

    expected = [
        (mapping[("test", "2")], mapping[("test", "2")], 1, 1),
        (mapping[('test', "1")], mapping[("test", "1")], 1, 1),
        (mapping[('test', "2")], mapping[("test", "1")], 0.2, 0.8),
        (mapping[('biosphere', "1")], mapping[("test", "1")], 50, 500),
        (mapping[('biosphere', "2")], mapping[("test", "2")], -0.43, -0.41),
    ]

    concatenated = np.hstack((pv.tech_params, pv.bio_params))
    for row, col, mn, mx in expected:
        mask = (concatenated['input'] == row) * (concatenated['output'] == col)
        assert mask.sum() == 1
        for sample in samples:
            assert mn <= sample[:mask.shape[0]][mask] <= mx

ext: py

reason: import numpy


text:
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Xu Yan
@file: utils.py
@time: 2021/10/21 21:45
'''
import numpy as np

def roty(t):
    """Rotation about the y-axis."""
    c = np.cos(t)
    s = np.sin(t)
    return np.array([[c, -s,  0],
                     [s,  c,  0],
                     [0,  0,  1]])

def get_3d_box(box_size, heading_angle, center):
    ''' box_size is array(l,w,h), heading_angle is radius clockwise from pos x axis, center is xyz of box center
        output (8,3) array for 3D box cornders
        Similar to utils/compute_orientation_3d
    '''
    R = roty(heading_angle)
    l,w,h = box_size
    # x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2]
    # y_corners = [h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2]
    # z_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2]
    x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2]
    y_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2]
    z_corners = [h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2]
    corners_3d = np.dot(R, np.vstack([x_corners,y_corners,z_corners]))
    corners_3d[0,:] = corners_3d[0,:] + center[0]
    corners_3d[1,:] = corners_3d[1,:] + center[1]
    corners_3d[2,:] = corners_3d[2,:] + center[2]
    corners_3d = np.transpose(corners_3d)
    return corners_3d

def write_ply(verts, colors, indices, output_file):
    if colors is None:
        colors = np.zeros_like(verts)
    if indices is None:
        indices = []

    file = open(output_file, 'w')
    file.write('ply \n')
    file.write('format ascii 1.0\n')
    file.write('element vertex {:d}\n'.format(len(verts)))
    file.write('property float x\n')
    file.write('property float y\n')
    file.write('property float z\n')
    file.write('property uchar red\n')
    file.write('property uchar green\n')
    file.write('property uchar blue\n')
    file.write('element face {:d}\n'.format(len(indices)))
    file.write('property list uchar uint vertex_indices\n')
    file.write('end_header\n')
    for vert, color in zip(verts, colors):
        file.write("{:f} {:f} {:f} {:d} {:d} {:d}\n".format(vert[0], vert[1], vert[2], int(color[0] * 255),
                                                            int(color[1] * 255), int(color[2] * 255)))
    for ind in indices:
        file.write('3 {:d} {:d} {:d}\n'.format(ind[0], ind[1], ind[2]))
    file.close()

def box2obj(box, objname):
    corners = box.corners().T
    with open(objname, 'w') as f:
        for corner in corners:
            f.write('v %f %f %f\n' % (corner[0], corner[1], corner[2]))
        f.write('f %d %d %d %d\n' % (1, 2, 3, 4))
        f.write('f %d %d %d %d\n' % (5, 6, 7, 8))
        f.write('f %d %d %d %d\n' % (1, 5, 8, 4))
        f.write('f %d %d %d %d\n' % (2, 6, 7, 3))
        f.write('f %d %d %d %d\n' % (1, 2, 6, 5))
        f.write('f %d %d %d %d\n' % (4, 3, 7, 8))

def write_bbox(corners, mode, output_file):
    """
    bbox: (cx, cy, cz, lx, ly, lz, r), center and length in three axis, the last is the rotation
    output_file: string
    """

    def create_cylinder_mesh(radius, p0, p1, stacks=10, slices=10):

        import math

        def compute_length_vec3(vec3):
            return math.sqrt(vec3[0] * vec3[0] + vec3[1] * vec3[1] + vec3[2] * vec3[2])

        def rotation(axis, angle):
            rot = np.eye(4)
            c = np.cos(-angle)
            s = np.sin(-angle)
            t = 1.0 - c
            axis /= compute_length_vec3(axis)
            x = axis[0]
            y = axis[1]
            z = axis[2]
            rot[0, 0] = 1 + t * (x * x - 1)
            rot[0, 1] = z * s + t * x * y
            rot[0, 2] = -y * s + t * x * z
            rot[1, 0] = -z * s + t * x * y
            rot[1, 1] = 1 + t * (y * y - 1)
            rot[1, 2] = x * s + t * y * z
            rot[2, 0] = y * s + t * x * z
            rot[2, 1] = -x * s + t * y * z
            rot[2, 2] = 1 + t * (z * z - 1)
            return rot

        verts = []
        indices = []
        diff = (p1 - p0).astype(np.float32)
        height = compute_length_vec3(diff)
        for i in range(stacks + 1):
            for i2 in range(slices):
                theta = i2 * 2.0 * math.pi / slices
                pos = np.array([radius * math.cos(theta), radius * math.sin(theta), height * i / stacks])
                verts.append(pos)
        for i in range(stacks):
            for i2 in range(slices):
                i2p1 = math.fmod(i2 + 1, slices)
                indices.append(np.array([(i + 1) * slices + i2, i * slices + i2, i * slices + i2p1], dtype=np.uint32))
                indices.append(
                    np.array([(i + 1) * slices + i2, i * slices + i2p1, (i + 1) * slices + i2p1], dtype=np.uint32))
        transform = np.eye(4)
        va = np.array([0, 0, 1], dtype=np.float32)
        vb = diff
        vb /= compute_length_vec3(vb)
        axis = np.cross(vb, va)
        angle = np.arccos(np.clip(np.dot(va, vb), -1, 1))
        if angle != 0:
            if compute_length_vec3(axis) == 0:
                dotx = va[0]
                if (math.fabs(dotx) != 1.0):
                    axis = np.array([1, 0, 0]) - dotx * va
                else:
                    axis = np.array([0, 1, 0]) - va[1] * va
                axis /= compute_length_vec3(axis)
            transform = rotation(axis, -angle)
        transform[:3, 3] += p0
        verts = [np.dot(transform, np.array([v[0], v[1], v[2], 1.0])) for v in verts]
        verts = [np.array([v[0], v[1], v[2]]) / v[3] for v in verts]

        return verts, indices

    def get_bbox_edges(bbox_min, bbox_max):
        def get_bbox_verts(bbox_min, bbox_max):
            verts = [
                np.array([bbox_min[0], bbox_min[1], bbox_min[2]]),
                np.array([bbox_max[0], bbox_min[1], bbox_min[2]]),
                np.array([bbox_max[0], bbox_max[1], bbox_min[2]]),
                np.array([bbox_min[0], bbox_max[1], bbox_min[2]]),

                np.array([bbox_min[0], bbox_min[1], bbox_max[2]]),
                np.array([bbox_max[0], bbox_min[1], bbox_max[2]]),
                np.array([bbox_max[0], bbox_max[1], bbox_max[2]]),
                np.array([bbox_min[0], bbox_max[1], bbox_max[2]])
            ]
            return verts

        box_verts = get_bbox_verts(bbox_min, bbox_max)
        edges = [
            (box_verts[0], box_verts[1]),
            (box_verts[1], box_verts[2]),
            (box_verts[2], box_verts[3]),
            (box_verts[3], box_verts[0]),

            (box_verts[4], box_verts[5]),
            (box_verts[5], box_verts[6]),
            (box_verts[6], box_verts[7]),
            (box_verts[7], box_verts[4]),

            (box_verts[0], box_verts[4]),
            (box_verts[1], box_verts[5]),
            (box_verts[2], box_verts[6]),
            (box_verts[3], box_verts[7])
        ]
        return edges

    radius = 0.03
    offset = [0, 0, 0]
    verts = []
    indices = []
    colors = []

    box_min = np.min(corners, axis=0)
    box_max = np.max(corners, axis=0)
    palette = {
        0: [0, 255, 0],  # gt
        1: [0, 0, 255]  # pred
    }
    chosen_color = palette[mode]
    edges = get_bbox_edges(box_min, box_max)
    for k in range(len(edges)):
        cyl_verts, cyl_ind = create_cylinder_mesh(radius, edges[k][0], edges[k][1])
        cur_num_verts = len(verts)
        cyl_color = [[c / 255 for c in chosen_color] for _ in cyl_verts]
        cyl_verts = [x + offset for x in cyl_verts]
        cyl_ind = [x + cur_num_verts for x in cyl_ind]
        verts.extend(cyl_verts)
        indices.extend(cyl_ind)
        colors.extend(cyl_color)

    write_ply(verts, colors, indices, output_file)

def write_obj(points, file, rgb=False):
    fout = open('%s.obj' % file, 'w')
    for i in range(points.shape[0]):
        if not rgb:
            fout.write('v %f %f %f %d %d %d\n' % (
                points[i, 0], points[i, 1], points[i, 2], 255, 255, 0))
        else:
            fout.write('v %f %f %f %d %d %d\n' % (
                points[i, 0], points[i, 1], points[i, 2], points[i, -3] * 255, points[i, -2] * 255,
                points[i, -1] * 255))

max_stars_repo_name: Ghostish/BAT

max_issues_repo_name: guzuoxu/BAT

max_forks_repo_name: guzuoxu/BAT


text:
# given the HDF file with 3-hr rainfall data,
# construct the one with daily accumulations

import os
import time
import numpy as np
# from pyhdf.SD import SD, SDC
import h5py

# Office_PC = False
# Cluster = True
# if Office_PC:
#     datadir ='C:\\Users\\ez23\\Desktop\\data_3B42_3hourly'
#     outdir  = 'C:\\Users\\ez23\\Desktop\\data_TMPA_conus_time_series'
# elif Cluster:
outdir  = os.path.join('..', 'data', 'tmpa_conus_data')
start_time = time.time()

onlyconus=False

if onlyconus: # for CONUS domain
    inputfile = 'data_tmpa_3h.hdf5'
    outputfile = 'data_tmpa_daily.hdf5'
else: # for WORLD domain
    inputfile = 'data_tmpa_world_3h.hdf5'
    outputfile = 'data_tmpa_world_daily.hdf5'

with h5py.File( os.path.join(outdir, inputfile), 'r') as f:
    trset = f['prcp']
    mylat = f['lat'][:]
    mylon = f['lon'][:]
    alldates = f['dates'][:]
    # also read and write attributes of interest
    nb = trset.attrs['north_bound']
    sb = trset.attrs['south_bound']
    wb = trset.attrs['west_bound']
    eb = trset.attrs['east_bound']
    sd = trset.attrs['start_date']
    ed = trset.attrs['end_date']
    sr =  trset.attrs['space_res']
    fc = trset.attrs['first_corner']
    rows = trset.attrs['rows']
    cols = trset.attrs['cols']

    nblon = np.size(mylon)
    nblat = np.size(mylat)

    # we compute daily totals only where all 8 3-hr values are non -missing
    # and otherwise mark the day with -9999
    # note: data must be already in 3-hr accumulations
    mydates = np.unique(alldates)
    ndates = np.size(mydates)

    with h5py.File( os.path.join(outdir,outputfile), 'w') as ff:
        dset = ff.create_dataset('prcp', (nblon, nblat, ndates),
                                           chunks = (1, 1, ndates) , dtype = 'f')
        dset2 = ff.create_dataset('lat', (nblat,), dtype = 'f')
        dset2[:] = mylat
        dset3 = ff.create_dataset('lon', (nblon,), dtype = 'f')
        dset3[:] = mylon
        dset4 = ff.create_dataset('dates', (ndates,), dtype = 'int32')
        dset4[:] = mydates

        for ii in range(nblon):
            for jj in range(nblat):
                sample = trset[ii,jj,:]
                daily = np.zeros(ndates)
                for kk in range(ndates):
                    mydate = mydates[kk]
                    mysample = sample[alldates == mydate]
                    non_missing = np.logical_and(mysample > -0.1, ~np.isnan(mysample) )
                    mysample2 = mysample[non_missing]
                    if np.size(mysample2) == 8:
                        daily[kk] = np.sum(mysample2)
                        # dset[ii,jj,kk] = np.sum(mysample2)
                    else:
                        daily[kk] = -9999
                        # dset[ii,jj,kk] = -9999
                dset[ii,jj,:] = daily

        dset.attrs['north_bound'] = nb
        dset.attrs['south_bound'] = sb
        dset.attrs['west_bound'] = wb
        dset.attrs['east_bound'] = eb
        dset.attrs['start_date'] =sd
        dset.attrs['end_date'] = ed
        dset.attrs['variable'] = 'PRCP Daily Accumulation [mm/day]'
        dset.attrs['time_res'] = 'daily'
        dset.attrs['space_res'] = sr
        dset.attrs['chunks_shape'] = '1 x 1 x ndates'
        dset.attrs['first_corner'] = fc
        dset.attrs['rows'] = rows
        dset.attrs['cols'] = cols

# TIME of EXECUTION of the script
execution_time = time.time() - start_time
print('extract_bounding_box:')
print("---execution time was %s minutes ---" % (execution_time/60))

max_stars_repo_name: EnricoZorzetto/downpy

max_issues_repo_name: EnricoZorzetto/downpy

max_forks_repo_name: EnricoZorzetto/downpy


text:
from PIL import Image
import numpy as np

power = np.array([1 << i for i in range(23, -1, -1)], dtype=np.uint32)

with Image.open("./Tour_Eiffel.bmp", mode='r') as im:
    ar = np.array(im)[2:, :-7]

ar = np.reshape(ar, (1780, 24)).astype(np.uint32)

colors = np.reshape(ar@power, (20, 89))

t = '

'
for row in colors:
    t += '
'
    for c in row:
        if c and (c-1) & c:
            code = hex(c)[2:].rjust(6, "0")
            if code[0] == code[1] and code[2] == code[3] and code[4] == code[5]:
                code = code[0]+code[2]+code[4]
            t += f'	'
        else:
            t += '	'
    t += "
"
t += "

"

with open("../../src/effiel.txt", "w") as f:
    f.write(t)
print("done")


text:
import gym
from gym.spaces import Box
import safety_gym
import tensorflow as tf
import numpy as np
from copy import deepcopy
from safety_gym.envs.suite import SafexpEnvBase

class SafetyPointWrapper(gym.Wrapper):
    def __init__(self, env_name):
        #self.registermode()
        environment = gym.make(env_name)
        super(SafetyPointWrapper, self).__init__(environment)

    def registermode(self):

        env_dict = gym.envs.registration.registry.env_specs.copy()
        for env in env_dict:
            if 'Safexp-PointSimpleGoal' in env:
                print("Remove {} from registry".format(env))
                del gym.envs.registration.registry.env_specs[env]

        bench_base = SafexpEnvBase('Simple', {'observe_goal_dist': False,
                                      'observe_goal_comp': False,
                                      'observe_box_comp': True,
                                      'observe_goal_lidar': True,
                                      'observe_box_lidar': True,
                                      'lidar_max_dist': 4,
                                      'lidar_num_bins': 5,
                                      })

        zero_base_dict = {'placements_extents': [-1, -1, 1, 1]}

        goal_all = {
            'task': 'goal',
            'goal_size': 0.3,
            'goal_keepout': 0.305,
            'hazards_size': 0.2,
            'hazards_keepout': 0.18,
        }

        # Shared among constrained envs (levels 1, 2)
        goal_constrained = {
            'constrain_hazards': True,
            'observe_hazards': True,
            'observe_vases': False,
        }

        # ==============#
        # Goal Level 0 #
        # ==============#
        goal0 = deepcopy(zero_base_dict)

        # ==============#
        # Goal Level 1 #
        # ==============#
        # Note: vases are present but unconstrained in Goal1.
        goal1 = {
            'placements_extents': [-1.5, -1.5, 1.5, 1.5],
            'hazards_num': 8,
        }
        goal1.update(goal_constrained)

        # ==============#
        # Goal Level 2 #
        # ==============#
        goal2 = {
            'placements_extents': [-2, -2, 2, 2],
            'observe_vases': True,
            'constrain_vases': True,
            'hazards_num': 10,
            'vases_num': 10
        }
        goal2.update(goal_constrained)

        # ==============#
        # Goal Level 3 #
        # ==============#
        goal_with_gremlins = {
            'gremlins_travel': 0.35,
            'gremlins_keepout': 0.4,
            'observe_hazards': False,
            'constrain_hazards': False,
            'observe_gremlins': True,
            'constrain_gremlins': True,
            'constrain_vases': True,
            'observe_vases': True,
            'placements_extents': [-1.5, -1.5, 1.5, 1.5],
            'vases_num': 2,
            'gremlins_num': 3,
        }

        bench_goal_base = bench_base.copy('Goal', goal_all)

        bench_goal_base.register('0', goal0)
        bench_goal_base.register('1', goal1)
        bench_goal_base.register('2', goal2)
        bench_goal_base.register('3', goal_with_gremlins)

class SafetyPointEnv(SafetyPointWrapper):
    def __init__(self):
        super().__init__("Safexp-PointSimpleGoal1-v0")
        offset = 0
        observation_space_summary = "Observation space indices are: "
        self.sensor_offset_table = dict()
        low = []
        high = []
        for k, value in sorted(self.env.obs_space_dict.items()):
            k_size = np.prod(value.shape)
            self.sensor_offset_table[k] = slice(offset, offset + k_size)
            key_low, key_high = self.resolve_observation_limits(k, k_size)
            low += key_low
            high += key_high
            observation_space_summary += \
                (k + " [" + str(offset) + ", " + str(offset + k_size) + ") " + "\n")
            offset += k_size
        self._scorer = SafetyGymStateScorer(
            self.env.config,
            self.sensor_offset_table)
        self.observation_space = Box(np.asarray(low), np.asarray(high), dtype=np.float32)
        dummy_observation = self.env.reset()
        assert dummy_observation.shape[0] == self.observation_space.shape[0]

    def resolve_observation_limits(self, key, dim):
        if key == 'box_compass':
            return [-1.0] * self.env.compass_shape, [1.0] * self.env.compass_shape
        elif key == 'box_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'goal_dist':
            return [-np.inf], [np.inf]
        elif key == 'goal_compass':
            return [-1.0] * self.env.compass_shape, [1.0] * self.env.compass_shape
        elif key == 'goal_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'remaining':
            return [0.0], [1.0]
        elif key == 'walls_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'hazards_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'vases_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'gremlins_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'pillars_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        elif key == 'buttons_lidar':
            return [0.0] * self.env.lidar_num_bins, [1.0] * self.env.lidar_num_bins
        else:
            return [-np.inf] * dim, [np.inf] * dim

    def get_reward(self, obs, acs, *args, **kwargs):
        return self._scorer.reward(obs, *args, **kwargs)

    def get_cost(self, obs, acs, *args, **kwargs):
        return self._scorer.cost(obs)

    def fix_observation(self, observation):
        if self.observe_goal_dist:
            # Predicting distances in exponential-space seems to really hold back the model from learning anything.
            observation[self.sensor_offset_table['goal_dist']] = \
                -np.log(observation[self.sensor_offset_table['goal_dist']])
        if self.observe_sensors:
            observation[self.sensor_offset_table['accelerometer']][2] += np.random.normal(loc=0, scale=0.01)
        if self.observe_hazards:
            observation[self.sensor_offset_table['hazards_lidar']] = \
                1.0 - observation[self.sensor_offset_table['hazards_lidar']]
        if self.observe_goal_lidar:
            observation[self.sensor_offset_table['goal_lidar']] = \
                1.0 - observation[self.sensor_offset_table['goal_lidar']]
        if self.observe_vases:
            observation[self.sensor_offset_table['vases_lidar']] = \
                1.0 - observation[self.sensor_offset_table['vases_lidar']]
        if self.observe_pillars:
            observation[self.sensor_offset_table['pillars_lidar']] = \
                1.0 - observation[self.sensor_offset_table['pillars_lidar']]
        if self.observe_buttons:
            observation[self.sensor_offset_table['buttons_lidar']] = \
                1.0 - observation[self.sensor_offset_table['buttons_lidar']]
        if self.observe_gremlins:
            observation[self.sensor_offset_table['gremlins_lidar']] = \
                1.0 - observation[self.sensor_offset_table['gremlins_lidar']]
        return observation

    def step(self, action):
        observation, reward, done, info = self.env.step(action)
        return self.fix_observation(observation), reward, done, info

    def reset(self, **kwargs):
        observation = self.env.reset()
        return self.fix_observation(observation)

class SafetyGymStateScorer(object):
    def __init__(self, config, sensor_offset_table):
        for key, value in config.items():
            setattr(self, key, value)
        self.sensor_offset_table = sensor_offset_table

    def reward(self, observations, next_observations):
        reward = tf.zeros((tf.shape(observations)[0],))
        goal_achieved = tf.zeros_like(reward, dtype=tf.bool)
        # Distance from robot to goal
        if self.task == 'goal':
            dist_goal = self.goal_distance_metric(observations)
            next_dist_goal = self.goal_distance_metric(next_observations)
            goal_achieved = tf.less_equal(dist_goal, self.goal_size * 0.8)
            reward += (dist_goal - next_dist_goal) * self.reward_distance + tf.cast(goal_achieved,
                                                                                tf.float32) * self.reward_goal
        # Distance from robot to box
        elif self.task == 'push':
            box_observed = tf.math.reduce_any(
                tf.greater(observations[:, self.sensor_offset_table['box_lidar']], 0.0), axis=1)
            next_box_observed = tf.math.reduce_any(
                tf.greater(next_observations[:, self.sensor_offset_table['box_lidar']], 0.0), axis=1)
            rewards_gate = tf.logical_and(box_observed, next_box_observed)
            dist_box_goal, dist_box = self.push_distance_metric(observations)
            next_dist_box_goal, next_dist_box = self.push_distance_metric(next_observations)
            goal_achieved = tf.less_equal(dist_box_goal, self.goal_size)
            reward += ((dist_box_goal - next_dist_box_goal) * self.reward_box_goal +
                       tf.cast(goal_achieved, tf.float32) * self.reward_goal) * tf.cast(rewards_gate, tf.float32)
            gate_dist_box_reward = tf.greater(dist_box, self.box_null_dist * self.box_size)
            reward += ((dist_box - next_dist_box) * self.reward_box_dist *
                       tf.cast(gate_dist_box_reward, tf.float32)) * tf.cast(rewards_gate, tf.float32)
        # Intrinsic reward for uprightness
        if self.reward_orientation:
            accelerometer = observations[:, self.sensor_offset_table['acceleration']]
            zalign = (accelerometer / tf.linalg.norm(accelerometer, axis=1, keepdims=True))
            reward += self.reward_orientation_scale * tf.linalg.tensordot(zalign, ([0.0, 0.0, 1.0]))
        # Clip reward
        if self.reward_clip:
            reward = tf.clip_by_value(reward, -self.reward_clip, self.reward_clip)
        return reward, goal_achieved

    def cost(self, observations):
        cost = tf.zeros((tf.shape(observations)[0],), dtype=tf.float32)
        # Conctacts processing
        if self.constrain_vases:
            vases_lidar = observations[:, self.sensor_offset_table['vases_lidar']]
            vases_dist = self.closest_distance(vases_lidar)
            cost += tf.cast(tf.less_equal(vases_dist, self.vases_size), dtype=tf.float32)
        if self.constrain_hazards:
            hazards_lidar = observations[:, self.sensor_offset_table['hazards_lidar']]
            hazards_dist = self.closest_distance(hazards_lidar)
            cost += tf.cast(tf.less_equal(hazards_dist, self.hazards_size), dtype=tf.float32)
        if self.constrain_pillars:
            pillars_lidar = observations[:, self.sensor_offset_table['pillars_lidar']]
            pillars_dist = self.closest_distance(pillars_lidar)
            cost += tf.cast(tf.less_equal(pillars_dist, self.pillars_size), dtype=tf.float32)
        if self.constrain_gremlins:
            gremlins_lidar = observations[:, self.sensor_offset_table['gremlins_lidar']]
            gremlins_dist = self.closest_distance(gremlins_lidar)
            cost += tf.cast(tf.less_equal(gremlins_dist, self.gremlins_size), dtype=tf.float32)
        if self.constrain_indicator:
            return tf.cast(tf.greater(cost, 0.0), dtype=tf.float32)
        return cost

    def goal_distance_metric(self, observations):
        if self.observe_goal_lidar:
            goal_lidar = observations[:, self.sensor_offset_table['goal_lidar']]
            return self.closest_distance(goal_lidar)
        elif self.observe_goal_dist:
            # Just a fancy way to clip negative values.
            return tf.squeeze(tf.nn.relu(observations[:, self.sensor_offset_table['goal_dist']]))
        else:
            raise NotImplementedError

    def push_distance_metric(self, observations):
        box_lidar = observations[:, self.sensor_offset_table['box_lidar']]
        dist_box = self.closest_distance(box_lidar)
        dist_goal = -tf.math.log(observations[:, self.sensor_offset_table['goal_dist']])
        box_direction = self.average_direction(box_lidar)
        goal_position = dist_goal * observations[:, self.sensor_offset_table['goal_compass']]
        box_position = dist_box * box_direction
        dist_box_goal = tf.linalg.norm(goal_position - box_position, axis=1)
        return dist_box_goal, dist_box

    def closest_distance(self, lidar_measurement):
        return tf.reduce_min(
            tf.clip_by_value(self.lidar_max_dist - self.lidar_max_dist * (1.0 - lidar_measurement), 0.0,
                             self.lidar_max_dist),
            axis=1)

    def average_direction(self, lidar_measurement):
        angles = (tf.range(self.lidar_num_bins) + 0.5) * 2.0 * np.pi / self.lidar_num_bins
        x = tf.math.cos(angles)
        x = tf.broadcast_to(
            x, (tf.shape(lidar_measurement)[0], tf.shape(x)[0])
        )
        y = tf.math.sin(angles)
        y = tf.broadcast_to(
            y, (tf.shape(lidar_measurement)[0], tf.shape(y)[0])
        )
        averaged_x = tf.reduce_sum(tf.linalg.tensordot(x, lidar_measurement + 1e-7, axis=1))
        averaged_y = tf.reduce_sum(tf.linalg.tensordot(y, lidar_measurement + 1e-7, axis=1))
        return tf.stack((averaged_x, averaged_y), axis=1)

max_stars_repo_name: rudrasohan/mbpo

max_issues_repo_name: rudrasohan/mbpo

max_forks_repo_name: rudrasohan/mbpo


text:
import abc
from collections import OrderedDict

import mujoco_py
import numpy as np
import sys
from multiworld.envs.mujoco.mujoco_env import MujocoEnv
from gym.spaces import Box, Dict
from multiworld.core.serializable import Serializable
from multiworld.envs.env_util import (
    get_stat_in_paths,
    create_stats_ordered_dict, get_asset_full_path,
)
from multiworld.core.multitask_env import MultitaskEnv
from multiworld.envs.mujoco.sawyer_xyz.base import SawyerXYZEnv

class SawyerDoorEnv(
    SawyerXYZEnv,
    MultitaskEnv,
    Serializable,
    metaclass=abc.ABCMeta,
):
    def __init__(
        self,
        goal_low=None,
        goal_high=None,
        action_reward_scale=0,
        reward_type='angle_difference',
        indicator_threshold=(.02, .03),
        fix_goal=False,
        fixed_goal=(0, .45, .12, -.25),
        reset_free=False,
        fixed_hand_z=0.12,
        hand_low=(-0.25, 0.3, .12),
        hand_high=(0.25, 0.6, .12),
        target_pos_scale=1,
        target_angle_scale=1,
        min_angle=-1.5708,
        max_angle=0,
        xml_path='sawyer_xyz/sawyer_door_pull.xml',
        **sawyer_xyz_kwargs
    ):
        self.quick_init(locals())
        self.model_name = get_asset_full_path(xml_path)
        SawyerXYZEnv.__init__(
            self,
            self.model_name,
            hand_low=hand_low,
            hand_high=hand_high,
            **sawyer_xyz_kwargs
        )
        MultitaskEnv.__init__(self)

        self.reward_type = reward_type
        self.indicator_threshold = indicator_threshold

        self.fix_goal = fix_goal
        self.fixed_goal = np.array(fixed_goal)
        self._state_goal = None
        self.fixed_hand_z = fixed_hand_z

        self.action_space = Box(np.array([-1, -1]), np.array([1, 1]), dtype=np.float32)
        self.state_space = Box(
            np.concatenate((hand_low, [min_angle])),
            np.concatenate((hand_high, [max_angle])),
            dtype=np.float32,
        )
        if goal_low is None:
            goal_low = self.state_space.low
        if goal_high is None:
            goal_high = self.state_space.high
        self.goal_space = Box(
            np.array(goal_low),
            np.array(goal_high),
            dtype=np.float32,
        )
        self.observation_space = Dict([
            ('observation', self.state_space),
            ('desired_goal', self.goal_space),
            ('achieved_goal', self.state_space),
            ('state_observation', self.state_space),
            ('state_desired_goal', self.goal_space),
            ('state_achieved_goal', self.state_space),
        ])
        self.action_reward_scale = action_reward_scale
        self.target_pos_scale = target_pos_scale
        self.target_angle_scale = target_angle_scale
        self.reset_free = reset_free
        self.door_angle_idx = self.model.get_joint_qpos_addr('doorjoint')
        self.reset()

    def step(self, action):
        self.set_xy_action(action[:2], self.fixed_hand_z)
        u = np.zeros(8)
        u[7] = 1
        self.do_simulation(u, self.frame_skip)
        info = self._get_info()
        ob = self._get_obs()
        reward = self.compute_reward(action, ob)
        done = False
        return ob, reward, done, info

    def _get_obs(self):
        pos = self.get_endeff_pos()
        angle = self.get_door_angle()
        flat_obs = np.concatenate((pos, angle))
        return dict(
            observation=flat_obs,
            desired_goal=self._state_goal,
            achieved_goal=flat_obs,
            state_observation=flat_obs,
            state_desired_goal=self._state_goal,
            state_achieved_goal=flat_obs,
        )

    def _get_info(self):
        angle_diff = np.abs(self.get_door_angle() - self._state_goal[-1])[0]
        hand_dist = np.linalg.norm(self.get_endeff_pos() - self._state_goal[:3])
        info = dict(
            angle_difference=angle_diff,
            angle_success=(angle_diff < self.indicator_threshold[0]).astype(
                float),
            hand_distance=hand_dist,
            hand_success=(hand_dist < self.indicator_threshold[1]).astype(
                float),
            total_distance=angle_diff + hand_dist
        )
        return info

    def get_door_angle(self):
        return np.array([self.data.get_joint_qpos('doorjoint')])

    @property
    def endeff_id(self):
        return self.model.body_names.index('leftclaw')

    def compute_rewards(self, actions, obs):
        achieved_goals = obs['state_achieved_goal']
        desired_goals = obs['state_desired_goal']
        actual_angle = achieved_goals[:, -1]
        goal_angle = desired_goals[:, -1]
        pos = achieved_goals[:, :3]
        goal_pos = desired_goals[:, :3]
        angle_diff = np.abs(actual_angle - goal_angle)
        pos_dist = np.linalg.norm(pos - goal_pos, axis=1)
        if self.reward_type == 'angle_diff_and_hand_distance':
            r = - (
                angle_diff * self.target_angle_scale
                + pos_dist * self.target_pos_scale
            )
        elif self.reward_type == 'angle_difference':
            r = - angle_diff * self.target_angle_scale
        elif self.reward_type =='angle_success':
            r = (angle_diff < self.indicator_threshold[0]).astype(
                float)
        elif self.reward_type == 'hand_success':
            r = -(angle_diff > self.indicator_threshold[0] or pos_dist >
                  self.indicator_threshold[1]).astype(float)
        else:
            raise NotImplementedError("Invalid/no reward type.")
        return r

    def reset_model(self):
        if not self.reset_free:
            self._reset_hand()
            self._set_door_pos(0)
        goal = self.sample_goal()
        self.set_goal(goal)
        self.reset_mocap_welds()
        return self._get_obs()

    def reset(self):
        # super.reset() does not account for reset-free logic.
        ob = self.reset_model()
        if self.viewer is not None:
            self.viewer_setup()
        return ob

    def _reset_hand(self):
        velocities = self.data.qvel.copy()
        angles = self.data.qpos.copy()
        # Do this to make sure the robot isn't in some weird configuration.
        angles[:7] = self.init_arm_angles
        self.set_state(angles.flatten(), velocities.flatten())
        for _ in range(10):
            self.data.set_mocap_pos('mocap', np.array([0, 0.5, 0.02]))
            self.data.set_mocap_quat('mocap', np.array([1, 0, 1, 0]))
            self.do_simulation(None, self.frame_skip)
    @property
    def init_arm_angles(self):
        return [1.78026069e+00, - 6.84415781e-01, - 1.54549231e-01,
                2.30672090e+00, 1.93111471e+00,  1.27854012e-01,
                1.49353907e+00]

    def _set_door_pos(self, pos):
        qpos = self.data.qpos.copy()
        qvel = self.data.qvel.copy()
        qpos[self.door_angle_idx] = pos
        qvel[self.door_angle_idx] = 0
        self.set_state(qpos.flatten(), qvel.flatten())

    ''' Multitask Functions '''

    @property
    def goal_dim(self):
        return 4

    def set_goal(self, goal):
        self._state_goal = goal['state_desired_goal']

    def sample_goals(self, batch_size):
        if self.fix_goal:
            goals = np.repeat(
                self.fixed_goal.copy()[None],
                batch_size,
                0
            )
        else:
            goals = np.random.uniform(
                self.goal_space.low,
                self.goal_space.high,
                size=(batch_size, self.goal_space.low.size),
            )
        # This only works for 2D control
        goals[:, 2] = self.fixed_hand_z
        return {
            'desired_goal': goals,
            'state_desired_goal': goals,
        }

    def set_to_goal_angle(self, angle):
        self._state_goal[-1] = angle.copy()
        qpos = self.data.qpos.flat.copy()
        qvel = self.data.qvel.flat.copy()
        qpos[-1] = angle.copy()
        qvel[-1] = 0
        self.set_state(qpos, qvel)

    def set_to_goal_pos(self, xyz):
        for _ in range(10):
            self.data.set_mocap_pos('mocap', np.array(xyz))
            self.data.set_mocap_quat('mocap', np.array([1, 0, 1, 0]))
            u = np.zeros(8)
            self.do_simulation(u, self.frame_skip)

    def get_goal(self):
        return {
            'desired_goal': self._state_goal,
            'state_desired_goal': self._state_goal,
        }

    def set_to_goal(self, goal):
        raise NotImplementedError("Hard to do because what if the hand is in "
                                  "the door? Use presampled goals.")

    def get_diagnostics(self, paths, prefix=''):
        statistics = OrderedDict()
        for stat_name in [
            'angle_difference',
            'angle_success',
            'hand_distance',
            'hand_success',
            'total_distance',
        ]:
            stat_name = stat_name
            stat = get_stat_in_paths(paths, 'env_infos', stat_name)
            statistics.update(create_stats_ordered_dict(
                '%s%s' % (prefix, stat_name),
                stat,
                always_show_all_stats=True,
            ))
            statistics.update(create_stats_ordered_dict(
                'Final %s%s' % (prefix, stat_name),
                [s[-1] for s in stat],
                always_show_all_stats=True,
            ))
        return statistics

    def get_env_state(self):
        base_state = super().get_env_state()
        goal = self._state_goal.copy()
        return base_state, goal

    def set_env_state(self, state):
        base_state, goal = state
        super().set_env_state(base_state)
        self._state_goal = goal

max_stars_repo_name: kelvinxu/multiworld

max_issues_repo_name: kelvinxu/multiworld

max_forks_repo_name: kelvinxu/multiworld


text:
import pickle
import matplotlib.pyplot as plt
import matplotlib as mpl
#mpl.use('pdf')
import itertools
import numpy as np
from datetime import datetime
import torch
from torch import nn
from torch import optim
import os
import sys
import pandas as pd

from utils.utilities import meter
from utils import make_histos
from utils.utilities import cartesian_converter
from utils.utilities import make_model
from utils import dataXZ

from nflows.transforms.autoregressive import MaskedUMNNAutoregressiveTransform
from nflows.flows.base import Flow
from nflows.distributions.normal import StandardNormal
from nflows.distributions.normal import DiagonalNormal
from nflows.transforms.base import CompositeTransform
from nflows.transforms.autoregressive import MaskedAffineAutoregressiveTransform
from nflows.transforms.permutations import ReversePermutation

dev = "cuda" if torch.cuda.is_available() else "cpu"
print(dev)
device = torch.device(dev)

#reonstruct an nflow model
#model_path = "models/"
model_path = "models/Cond/3features/"
feature_subset = [9,10,11,13,14,15] #All 16 features

print(" reading photon NF model ")
model_name = "TM-Final-UMNN_phot_3_10_80_128_-5.38.pt"
params = model_name.split("_")
num_features = int(params[2])
num_layers = int(params[3])
num_hidden_features = int(params[4])
training_sample_size = int(params[5])

print(num_features,num_layers,num_hidden_features,training_sample_size)

flow_g, optimizer_g = make_model(num_layers,num_features,num_hidden_features,device)

print("number of params: ", sum(p.numel() for p in flow_g.parameters()))
flow_g.load_state_dict(torch.load(model_path+model_name))
flow_g.eval()

print(" reading photon2 NF model ")
model_name = "TM-Final-UMNN_phot2_3_10_80_128_-6.04.pt"
params = model_name.split("_")
num_features = int(params[2])
num_layers = int(params[3])
num_hidden_features = int(params[4])
training_sample_size = int(params[5])

print(num_features,num_layers,num_hidden_features,training_sample_size)

flow_g2, optimizer_g2 = make_model(num_layers,num_features,num_hidden_features,device)

print("number of params: ", sum(p.numel() for p in flow_g2.parameters()))
flow_g2.load_state_dict(torch.load(model_path+model_name))
flow_g2.eval()

print("reading truth data")
train = dataXZ.dataXZ(feature_subset=feature_subset, file = "data/epgg_train.pkl", mode = "epgg")
truth_entire = train.truth.detach().numpy()
reco_entire = train.reco.detach().numpy()
print("done with reading truth data")

print("reading test data")
test = dataXZ.dataX(feature_subset=feature_subset, file = "data/epgg_test.pkl", mode = "epgg")
reco_test = test.reco.detach().numpy()
print("done with reading test data")

trials = 10000 #Number of overall loops

means = np.mean(reco_entire - truth_entire, axis = 1)
stds = np.std(reco_entire - truth_entire, axis = 1)

n_sample = 100
n_loop = len(reco_test)//n_sample

for loop_num in range(n_loop):
	print("new loop "+str(loop_num))

	truths_guess = []

	start = datetime.now()
	start_time = start.strftime("%H:%M:%S")
	print("Start Time =", start_time)

	for i in range(n_sample):

		maxtruth_g = []
		logprob_g = []
		maxtruth_g2 = []
		logprob_g2 = []

		#photon
		reco_g = reco_test[i+n_sample*loop_num:i+n_sample*loop_num+1, [0,1,2]]
		mean_g = means[[0,1,2]]
		std_g = stds[[0,1,2]]

		#photon2
		reco_g2 = reco_test[i+n_sample*loop_num:i+n_sample*loop_num+1, [3,4,5]]
		mean_g2 = means[[3,4,5]]
		std_g2 = stds[[3,4,5]]

		truth_g = reco_g + np.random.normal(mean_g, std_g, (trials, 3))
		truth_g2 = reco_g2 + np.random.normal(mean_g2, std_g2, (trials, 3))

		# for reco in reco_g:
		reco_useful = np.tile(reco_g, (trials, 1))
		reco_useful = torch.tensor(reco_useful, dtype=torch.float32).to(device)
		truth_g = torch.tensor(truth_g, dtype=torch.float32).to(device)
		logprob = flow_g.log_prob(inputs=reco_useful,context=truth_g)
		ind_max = np.argmax(logprob.cpu().detach().numpy())
		maxtruth_g.append(truth_g[ind_max:ind_max+1, :])
		logprob_g.append(logprob[ind_max])

		# for reco in reco_g:
		reco_useful = np.tile(reco_g2, (trials, 1))
		reco_useful = torch.tensor(reco_useful, dtype=torch.float32).to(device)
		truth_g2 = torch.tensor(truth_g2, dtype=torch.float32).to(device)
		logprob = flow_g2.log_prob(inputs=reco_useful,context=truth_g2)
		ind_max = np.argmax(logprob.cpu().detach().numpy())
		maxtruth_g2.append(truth_g[ind_max:ind_max+1, :])
		logprob_g2.append(logprob[ind_max])

		#photon
		truth_val_g = maxtruth_g[np.argmax(logprob_g)].cpu().detach().numpy()
		E_true_g = np.sqrt(truth_val_g[:, 0]**2 + truth_val_g[:, 1]**2  + truth_val_g[:, 2]**2).reshape((-1, 1))

		#photon
		truth_val_g2 = maxtruth_g2[np.argmax(logprob_g2)].cpu().detach().numpy()
		E_true_g2 = np.sqrt(truth_val_g2[:, 0]**2 + truth_val_g2[:, 1]**2  + truth_val_g2[:, 2]**2).reshape((-1, 1))

		NF_true = np.hstack( (E_true_g, truth_val_g, E_true_g2, truth_val_g2))
		truths_guess.append(NF_true)

	now = datetime.now()
	elapsedTime = (now - start )
	print("Current time is {}".format(now.strftime("%H:%M:%S")))
	print("Elapsed time is {}".format(elapsedTime))
	# print("Total estimated run time is {}".format(elapsedTime+elapsedTime/i*(max_range+1-i)))
	Truths = np.concatenate(truths_guess)
	df_Truths = pd.DataFrame(Truths)
	df_Truths.to_pickle("gendata/Cond/3features/UMNN/Truths_Test_pi0_{}.pkl".format(loop_num))#num_features,
	#     num_layers,num_hidden_features,training_sample_size,loop_num))
	#print(truths_guess )
	#print(truth_validation[0:n_sample, :])
	#print(reco_test[0:n_sample, :])
print("done")
quit()


text:
import os
# import sys
# reload(sys)
# sys.setdefaultencoding("utf-8")
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
# from torch.autograd import Variable
import argparse
import loaddata
import dataloader
import model
import scoring
import scoring_char
import transformer
import transformer_char
import numpy as np
import pickle
np.random.seed(7)

parser = argparse.ArgumentParser(description='Data')
parser.add_argument('--data', type=int, default=0, metavar='N',
                    help='data: can be 0,1,2,3,5,6,7 which specify a textdata file')
parser.add_argument('--externaldata', type=str, default='', metavar='S',
                    help='External database file. Default: Empty string')
parser.add_argument('--model', type=str, default='simplernn', metavar='S',
                    help='model type(simplernn, charcnn, bilstm). LSTM as default.')
parser.add_argument('--modelpath', type=str, default='models/simplernn_0_bestmodel.dat', metavar='S',
                    help='model file path')
parser.add_argument('--power', type=int, default=0, metavar='N',
                    help='Attack power')
parser.add_argument('--batchsize', type=int, default=128, metavar='N',
                    help='batch size')
parser.add_argument('--scoring', type=str, default='replaceone', metavar='N',
                    help='Scoring function.')
parser.add_argument('--transformer', type=str, default='homoglyph', metavar='N',
                    help='Transformer function.')
parser.add_argument('--maxbatches', type=int, default=None, metavar='B',
                    help='maximum batches of adv samples generated')
parser.add_argument('--advsamplepath', type=str, default=None, metavar='B',
                    help='advsamplepath: If default, will generate one according to parameters')
parser.add_argument('--dictionarysize', type=int, default=20000, metavar='B',
                    help='Size of the dictionary used in RNN model')
parser.add_argument('--charlength', type=int, default=1014, metavar='N',
                    help='length: default 1014')
parser.add_argument('--wordlength', type=int, default=500, metavar='N',
                    help='word length: default 500')
args = parser.parse_args()

torch.manual_seed(8)
torch.cuda.manual_seed(8)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

if args.model == "charcnn":
    args.datatype = "char"
elif args.model == "simplernn":
    args.datatype = "word"
elif args.model == "bilstm":
    args.datatype = "word"

if args.externaldata!='':
    if args.datatype == 'char':
        (data,numclass) = pickle.load(open(args.externaldata,'rb'))
        testchar = dataloader.Chardata(data, getidx = True)
        test_loader = DataLoader(testchar,batch_size=args.batchsize, num_workers=4, shuffle=False)
        alphabet = trainchar.alphabet
    elif args.datatype == 'word':
        (data,word_index,numclass) = pickle.load(open(args.externaldata,'rb'))
        testword = dataloader.Worddata(data, getidx = True)
        test_loader = DataLoader(testword,batch_size=args.batchsize, num_workers=4,shuffle=False)
else:
    if args.datatype == "char":
        (train,test,numclass) = loaddata.loaddata(args.data)
        trainchar = dataloader.Chardata(train, getidx = True)
        testchar = dataloader.Chardata(test, getidx = True)
        train_loader = DataLoader(trainchar,batch_size=args.batchsize, num_workers=4, shuffle = True)
        test_loader = DataLoader(testchar,batch_size=args.batchsize, num_workers=4, shuffle=True)
        alphabet = trainchar.alphabet
        maxlength = args.charlength
    elif args.datatype == "word":
        (train,test,tokenizer,numclass, rawtrain, rawtest) = loaddata.loaddatawithtokenize(args.data, nb_words = args.dictionarysize, datalen = args.wordlength, withraw=True)
        word_index = tokenizer.word_index
        trainword = dataloader.Worddata(train, getidx = True, rawdata = rawtrain)
        testword = dataloader.Worddata(test, getidx = True, rawdata = rawtest)
        train_loader = DataLoader(trainword,batch_size=args.batchsize, num_workers=4, shuffle = True)
        test_loader = DataLoader(testword,batch_size=args.batchsize, num_workers=4,shuffle=True)
        maxlength =  args.wordlength
if args.model == "charcnn":
    model = model.CharCNN(classes = numclass)
elif args.model == "simplernn":
    model = model.smallRNN(classes = numclass)
elif args.model == "bilstm":
    model = model.smallRNN(classes = numclass, bidirection = True)

print(model)

state = torch.load(args.modelpath)
model = model.to(device)
try:
    model.load_state_dict(state['state_dict'])
except:
    model = torch.nn.DataParallel(model).to(device)
    model.load_state_dict(state['state_dict'])
    model = model.module

alltimebest = 0
bestfeature = []
def recoveradv(rawsequence, index2word, inputs, advwords):
    filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n '
    rear_ct = len(rawsequence)
    advsequence = rawsequence[:]
    try:
        for i in range(inputs.size()[0]-1,-1,-1):
            wordi = index2word[inputs[i].item()]
            rear_ct = rawsequence[:rear_ct].rfind(wordi)
                # print(rear_ct)
            if inputs[i].item()>=3:
                advsequence = advsequence[:rear_ct] + advwords[i] + advsequence[rear_ct + len(wordi):]
    except:
        print('something went wrong')
    return advsequence

def attackchar(maxbatch = None):
    corrects = .0
    total_loss = 0
    model.eval()
    tgt = []
    adv = []
    origsample = []
    origsampleidx = []
    modified = []
    for dataid, data in enumerate(test_loader):
        print(dataid)
        if maxbatch!=None and dataid >= maxbatch:
            break
        inputs,target,idx,raw = data
        inputs, target = inputs.to(device), target.to(device)
        output = model(inputs)
        tgt.append(target)
        origsample.append(inputs)
        origsampleidx.append(idx)
        pred = torch.max(output, 1)[1].view(target.size())
        losses = torch.zeros(inputs.size()[0],inputs.size()[2])

        losses = scoring_char.scorefunc(args.scoring)(model, inputs, pred, numclass)

        sorted, indices = torch.sort(losses,dim = 1,descending=True)
        advinputs = inputs.clone()
        dt = inputs.sum(dim=1).int()
        for k in range(inputs.size()[0]):
            md = raw[k][:]
            md = md[::-1]
            j=0
            t=0
            while j < args.power and t<inputs.size()[2]:
                if dt[k,indices[k][t]].item()>0:
                    advinputs[k,:,indices[k][t]],nowchar = transformer_char.transform(args.transformer)(inputs, torch.max(advinputs[k,:,indices[k][t]],0)[1].item(), alphabet)
                    md = md[:indices[k][t].item()]+nowchar+md[indices[k][t].item()+1:]
                    j+=1
                t+=1
            md = md[::-1]
            modified.append(md)
        adv.append(advinputs)
        inputs2 = advinputs
        output2 = model(inputs2)
        pred2 = torch.max(output2, 1)[1].view(target.size())
        corrects += (pred2 == target).sum().item()
        for k in range(inputs.size()[0]):
            print(raw[k])
            print(pred[k].item())
            print(modified[k-inputs.size()[0]])
            print(pred2[k].item())

    target = torch.cat(tgt)
    advinputs = torch.cat(adv)
    origsamples = torch.cat(origsample)
    origsampleidx = torch.cat(origsampleidx)
    acc = corrects/advinputs.size(0)
    print('Accuracy %.5f' % (acc))
    f = open('attack_log.txt','a')
    f.write('%d\t%s\t%s\t%s\t%d\t%.2f\n' % (args.data,args.model,args.scoring,args.transformer,args.power,100*acc))
    if args.advsamplepath == None:
        advsamplepath = 'advsamples/%s_%d_%s_%s_%d.dat' % (args.model,args.data,args.scoring,args.transformer,args.power)
    else:
        advsamplepath = args.advsamplepath
    torch.save({'original':origsamples,'sampleid':origsampleidx,'advinputs':advinputs,'labels':target, 'adv_str':modified}, advsamplepath)

def attackword(maxbatch = None):
    corrects = .0
    total_loss = 0
    model.eval()
    wordinput = []
    tgt = []
    adv = []
    origsample = []
    origsampleidx = []

    for dataid, data in enumerate(test_loader):
        print(dataid)
        if maxbatch!=None and dataid >= maxbatch:
            break
        inputs,target, idx, raw = data
        inputs, target = inputs.to(device), target.to(device)
        origsample.append(inputs)
        origsampleidx.append(idx)
        tgt.append(target)
        wtmp = []
        output = model(inputs)
        pred = torch.max(output, 1)[1].view(target.size())

        losses = scoring.scorefunc(args.scoring)(model, inputs, pred, numclass)

        sorted, indices = torch.sort(losses,dim = 1,descending=True)

        advinputs = inputs.clone()

        for k in range(inputs.size()[0]):
            wtmp.append([])
            for i in range(inputs.size()[1]):
                if advinputs[k,i].item()>3:
                    wtmp[-1].append(index2word[advinputs[k,i].item()])
                else:
                    wtmp[-1].append('')
        for k in range(inputs.size()[0]):
            j = 0
            t = 0
            while j < args.power and t<inputs.size()[1]:
                if advinputs[k,indices[k][t]].item()>3:
                    word, advinputs[k,indices[k][t]] = transformer.transform(args.transformer)(advinputs[k,indices[k][t]].item(),word_index,index2word, top_words = args.dictionarysize)
                    wtmp[k][indices[k][t]] = word
                    print(word)
                    j+=1
                t+=1
        adv.append(advinputs)

        output2 = model(advinputs)
        pred2 = torch.max(output2, 1)[1].view(target.size())
        corrects += (pred2 == target).sum().item()
        for i in range(len(wtmp)):
            print(raw[i])
            print(pred[i].item())
            wordinputi = recoveradv(raw[i],index2word,inputs[i], wtmp[i])
            print(wordinputi)
            wordinput.append(wordinputi)
            print(pred2[i].item())

    target = torch.cat(tgt)
    advinputs = torch.cat(adv)
    origsamples = torch.cat(origsample)
    origsampleidx = torch.cat(origsampleidx)
    acc = corrects/advinputs.size(0)
    print('Accuracy %.5f' % (acc))
    f = open('attack_log.txt','a')
    f.write('%d\t%d\t%s\t%s\t%s\t%d\t%.2f\n' % (args.data,args.wordlength,args.model,args.scoring,args.transformer,args.power,100*acc))
    if args.advsamplepath == None:
        advsamplepath = 'advsamples/%s_%d_%s_%s_%d_%d.dat' % (args.model,args.data,args.scoring,args.transformer,args.power,args.wordlength)
    else:
        advsamplepath = args.advsamplepath
    torch.save({'original':origsamples,'sampleid':origsampleidx,'wordinput':wordinput,'advinputs':advinputs,'labels':target}, advsamplepath)

if args.datatype == "char":
    attackchar(maxbatch = args.maxbatches)
elif args.datatype == "word":
    index2word = {}
    index2word[0] = '[PADDING]'
    index2word[1] = '[START]'
    index2word[2] = '[UNKNOWN]'
    index2word[3] = ''
    if args.dictionarysize==20000:
        for i in word_index:
            if word_index[i]+3 < args.dictionarysize:
                index2word[word_index[i]+3]=i
    else:
        for i in word_index:
            if word_index[i] + 3 < args.dictionarysize:
                index2word[word_index[i]+3]=i
    attackword(maxbatch = args.maxbatches)

max_stars_repo_name: AnupKumarGupta/deepWordBug

max_issues_repo_name: AnupKumarGupta/deepWordBug

max_forks_repo_name: AnupKumarGupta/deepWordBug


text:
import base64
import io

import cv2
import numpy as np
from PIL import Image
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from tensorflow.keras.models import load_model

# global variables
labels = {
    0: 'book',
    1: 'chair',
    2: 'clothes',
    3: 'computer',
    4: 'drink',
    5: 'drum',
    6: 'family',
    7: 'football',
    8: 'go',
    9: 'hat',
    10: 'hello',
    11: 'kiss',
    12: 'like',
    13: 'play',
    14: 'school',
    15: 'street',
    16: 'table',
    17: 'university',
    18: 'violin',
    19: 'wall'
}

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/', methods=['POST', 'GET'])
def index():
    # home Page
    return render_template('index.html')

@socketio.on('image')
def image(data_image):
    # define empty buffer
    frame_buffer = np.empty((0, *dim, channels))

    # unpack request
    for data in data_image:
        # decode and convert the request in image
        img = Image.open(io.BytesIO(base64.b64decode(data[23:])))
        # converting RGB to BGR (opencv standard)
        frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        # process the frame
        frame_res = cv2.resize(frame, dim)
        frame_res = frame_res / 255.0
        # append the frame to buffer
        frame_resh = np.reshape(frame_res, (1, *frame_res.shape))
        frame_buffer = np.append(frame_buffer, frame_resh, axis=0)

    frame_buffer_resh = frame_buffer.reshape(1, *frame_buffer.shape)
    # model prediction
    predictions = model.predict(frame_buffer_resh)[0]
    # get the best prediction
    best_pred_idx = np.argmax(predictions)
    acc_best_pred = predictions[best_pred_idx]
    # check mislabeling
    if acc_best_pred > threshold:
        gloss = labels[best_pred_idx]
    else:
        gloss = 'none'
    # emit the predicted gloss to the client
    emit('response_back', gloss.upper())

if __name__ == '__main__':
    # settings
    dim = (224, 224)
    frames = 10
    channels = 3
    model_path = './model/WLASL20c_model.h5'
    threshold = .50

    # load model
    model = load_model(model_path)

    # start application
    socketio.run(app=app, host='127.0.0.1', port=5000)

max_stars_repo_path: web app/server.py

max_stars_repo_name: simonefinelli/ASL-Real-time-Recognition

max_issues_repo_path: web app/server.py

max_issues_repo_name: simonefinelli/ASL-Real-time-Recognition

max_forks_repo_path: web app/server.py

max_forks_repo_name: simonefinelli/ASL-Real-time-Recognition


text:
import cv2
import numpy as np
# from PIL import Image
import pytesseract
# import os

## (1) read
nameOfImage = "1000"
# img = cv2.imread("{0}/{0}.jpg".format(nameOfImage))
img = cv2.imread("qay_Page_1.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# (2) wipe out unimportant bits
findOrDestroy = "find"

def Find_And_Destroy(element, accuracy, findOrDestroy):
    if findOrDestroy == "find":
        color = (255,0,255)
        border = 3
    else:
        color = (255, 255, 255)
        border = -1
    elem = cv2.imread("elements/{0}.jpg".format(element))
    grayElem= cv2.cvtColor(elem, cv2.COLOR_BGR2GRAY)
    H,W= elem.shape[:2]
    result = cv2.matchTemplate(gray, grayElem, cv2.TM_CCOEFF_NORMED)
    loc = np.where(result >= accuracy)
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img, pt, (pt[0] + W, pt[1] + H), color, border)
        cv2.rectangle(gray, pt, (pt[0] + W, pt[1] + H), color, border)

# Put the cleaning into action
Find_And_Destroy("shadda",0.8, findOrDestroy)
Find_And_Destroy("shadda2",0.8, findOrDestroy)
Find_And_Destroy("shadda3",0.8, findOrDestroy)
Find_And_Destroy("semicolon",0.8, findOrDestroy)
Find_And_Destroy("colon",0.8, findOrDestroy)
Find_And_Destroy("period",0.9, findOrDestroy)
Find_And_Destroy("comma",0.6, findOrDestroy)
Find_And_Destroy("tanwin",0.7, findOrDestroy)
Find_And_Destroy("tanwin2",0.7, findOrDestroy)
Find_And_Destroy("longA",0.8, findOrDestroy)
Find_And_Destroy("doubleOpen",0.7, findOrDestroy)
Find_And_Destroy("doubleClose",0.7, findOrDestroy)
Find_And_Destroy("salla",0.75, findOrDestroy)
Find_And_Destroy("alayh",0.65, findOrDestroy)

# cv2.imwrite("1.selected.jpg", img)
# exit()
#
#
# To check if it is  found correctly change to "find" and uncomment the following lines
small = cv2.resize(img, (0,0), fx=0.3, fy=0.3)
cv2.imshow("find.jpg", small)
cv2.waitKey(0)
cv2.destroyAllWindows()
exit()

#Making lines more distinguished
blurred = cv2.GaussianBlur(gray, (21,21), 60,0)

## (2) threshold
th, threshed = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

## (3) minAreaRect on the nozeros
pts = cv2.findNonZero(threshed)
ret = cv2.minAreaRect(pts)

(cx,cy), (w,h), ang = ret
if w>h:
    w,h = h,w
    ang += 90

## (4) Find rotated matrix, do rotation
M = cv2.getRotationMatrix2D((cx,cy), ang, 1.0)
rotated = cv2.warpAffine(threshed, M, (img.shape[1], img.shape[0]))
normalRotated = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))

# cv2.imwrite("2a.rotated.jpg", rotated)
# cv2.imwrite("2b.normalRotated.jpg", normalRotated)
# exit()

## (5) Histogram to detect text block
histY = cv2.reduce(rotated,1, cv2.REDUCE_AVG).reshape(-1)
histX = cv2.reduce(rotated,0, cv2.REDUCE_AVG).reshape(-1)
i = 0
for value in histY:

    color = (int(value), int(2*value), int(value))
    cv2.line(normalRotated, (0, i), (value, i), color, 1)
    i = i+1
i = 0
for value in histX:

    color = (int(value), int(2*value), int(value))
    cv2.line(normalRotated, (i, 0), (i, value), color, 1)
    i = i+1
# cv2.imwrite("3.Histogram.jpg", normalRotated)
# exit()

## (6) Chop off left-right margins
threshhold = 5
H,W = img.shape[:2]
for pixel in range (0,W):
    if histX[pixel] < threshhold:
        cv2.line(normalRotated, (pixel, 0), (pixel, H), (255,255,255), 1)
# cv2.imwrite("4a.ChoppedLR.jpg", normalRotated)
# exit()

## (7) Chop off upper and lower. find and draw the upper and lower boundary of each lines

uppers = [y for y in range(H-1) if histY[y]<=threshhold and histY[y+1]>threshhold]
lowers = [y for y in range(H-1) if histY[y]>threshhold and histY[y+1]<=threshhold]

cv2.rectangle(normalRotated, (0,0), (W, lowers[0]), (255,255,255), -1)

line = cv2.imread("elements/division.jpg")
for i in range(1,len(uppers)):
    roi = normalRotated[uppers[i]-5:lowers[i]+4, 10:W-10]
    result = cv2.matchTemplate(roi, line, cv2.TM_CCOEFF_NORMED)
    loc = np.where(result >= 0.5)
    if loc[0].size:
        cv2.rectangle(normalRotated, (0,uppers[i]), (W, H), (255,255,255), -1)
        break
    else:
        continue

#cv2.imwrite("4b.ChoppedUL.jpg", normalRotated)
# exit()

# (8) Let us try and find the footnotes and dagger alif - and wipe them out of existence

def Wiping_Footnotes(template, accuracy):
    fn= cv2.imread("elements/"+template+".jpg")
    widthFN, heigthFN = fn.shape[:2]
    bandwidthUp = 6
    bandwidthDown = 30
    for i in range(1,len(uppers)):
        roi = normalRotated[uppers[i]-bandwidthUp:uppers[i]+bandwidthDown, 10:W-10]
        result = cv2.matchTemplate(roi, fn, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        if max_val > accuracy:
            cv2.rectangle(normalRotated, (10+max_loc[0], uppers[i]-bandwidthUp+max_loc[1]), (10+max_loc[0] + heigthFN, uppers[i]-bandwidthUp+max_loc[1] + widthFN), (255,255,255), -1)

for i in range(1,9):
    Wiping_Footnotes("note"+str(i), 0.7)
Wiping_Footnotes("notew", 0.7)
Wiping_Footnotes("note4b", 0.7)
Wiping_Footnotes("u", 0.75)
Wiping_Footnotes("a", 0.9)

# cv2.imwrite("5.cleaned.jpg", normalRotated)

## (9) Give the cleaned version to Tesseract

text = "\r\n" + "<pb n='{0}'/> \r\n".format(nameOfImage) + pytesseract.image_to_string(normalRotated, lang="ara")

with open("6.finalText.txt","a") as result:
    result.write(text)

max_stars_repo_name: dirkroorda/fusus

max_issues_repo_name: dirkroorda/fusus

max_forks_repo_name: dirkroorda/fusus


text:
import os
import numpy as np
from sklearn.cluster import KMeans

model = ["resnet18", "resnet50", "resnet152", "densenet121", "densenet201", "densenet161"]
pre = [0, 2, 4]
name = []
result = []
k = 2
for p in pre:
    for m in model:
        name.append("{}_({})".format(m, p))
        result.append("explainability{}explainability_iris_{}_{}".format(os.sep, m, p))

gradcam = []

for res in result:
    gradcam.append(np.load(os.sep.join(["results", res, "gradcam.npy"])))
gradcam = np.array(gradcam)

kmeans = KMeans(n_clusters=k, random_state=0)
kmeans.fit(gradcam)

print("k-means clusting with {} cluster".format(k))
for idx, (n, label) in enumerate(zip(name, kmeans.labels_)):
    print(n, ": ", label)

# for i in range(len(name)):
#     for j in range(len(name)):
#         print("dist: {} - {} = {}".format(name[i], name[j], np.linalg.norm(gradcam[i]-gradcam[j])))


text:
#!/usr/bin/env python2
"""
Based off of compare.py
"""
import argparse
import cv2
import itertools
import os
import numpy as np
np.set_printoptions(precision=2)
import openface

HOME = '/root/openface'
IMG_DIM = 96

modelDir = os.path.join(HOME, 'models')
dlibModelDir = os.path.join(modelDir, 'dlib')
openfaceModelDir = os.path.join(modelDir, 'openface')

align = openface.AlignDlib(
  os.path.join(dlibModelDir, "shape_predictor_68_face_landmarks.dat"))
net = openface.TorchNeuralNet(
  os.path.join(openfaceModelDir, 'nn4.small2.v1.t7'), IMG_DIM)

def align_face(img_path, save=False):
  img_bgr = cv2.imread(img_path)
  if img_bgr is None:
    raise Exception("Unable to load image '%s'" % img_path)

  # Convert to RGB
  img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
  # Get bounding box
  bbox = align.getLargestFaceBoundingBox(img_rgb)
  if bbox is None:
    raise Exception("Unable to find a face in '%s'" % img_path)

  print "Align '%s'" % img_path
  face = align.align(IMG_DIM, img_rgb, bbox,
    landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)

  if save:
    print "Save to '%s'" % save
    cv2.imwrite(save, face)
  return face

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('imgs', type=str, nargs='+', help="Input images.")
    parser.add_argument('--dlibFacePredictor', type=str, help="Path to dlib's face predictor.",
                        default=os.path.join(dlibModelDir, "shape_predictor_68_face_landmarks.dat"))
    parser.add_argument('--networkModel', type=str, help="Path to Torch network model.",
                        default=os.path.join(openfaceModelDir, 'nn4.small2.v1.t7'))
    parser.add_argument('--imgDim', type=int,
                        help="Default image dimension.", default=96)
    parser.add_argument('--verbose', action='store_true')

    return parser.parse_args()

if __name__ == '__main__':
  args = parse_args()
  [ align_face(p, os.path.basename(p)) for p in args.imgs ]
  pass


text:
import sys
import os
import datetime
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
from pprint import pprint
import sqlite3
import calendar
from datetime import datetime
from datetime import timedelta
import math
import numpy.polynomial.polynomial as poly

#mass fg, pk_ht, UNCORR
WHI_HG_incand_calib = [
[0.87206  ,52.50704	],
[1.12272  ,75.499	],
[1.4047   ,93.55246	],
[1.76501  ,127.22018],
[2.12533  ,165.82211],
[2.56397  ,211.81462],
[4.16188  ,379.35877],
[4.81984  ,436.83438],
[5.5718   ,482.78394],
[7.16971  ,630.59125],
[8.20366  ,694.59427],
[9.17493  ,786.56641],
[10.31854 ,853.84387],
[11.5248  ,907.95486],
[14.15666 ,1139.50203],
]

HG_pkht = np.array([row[1] for row in WHI_HG_incand_calib])
HG_mass = np.array([row[0] for row in WHI_HG_incand_calib])
HG_mass_corr = np.array([row[0]/0.7 for row in WHI_HG_incand_calib])
HG_fit = poly.polyfit(HG_pkht, HG_mass_corr, 1)
print 'HG fit', HG_fit

for line in WHI_HG_incand_calib:

	incand_pk_ht = line[1]
	uncorr_mass_fg = line[0]
	AD_corr_fit = HG_fit[0] + HG_fit[1]*incand_pk_ht# + HG_fit[2]*incand_pk_ht *incand_pk_ht

	line.append(AD_corr_fit)

HG_pk_ht = [row[1] for row in WHI_HG_incand_calib]
HG_uncorr_mass = [row[0] for row in WHI_HG_incand_calib]
HG_uncorr_fit = [row[2]*0.7 for row in WHI_HG_incand_calib]
HG_ADcorr_fit = [row[2] for row in WHI_HG_incand_calib]

fig = plt.figure(figsize=(12,10))
ax = fig.add_subplot(111)
ax.scatter(HG_pk_ht,HG_uncorr_mass,color='r', label = 'Uncorrected calibration')
ax.plot(HG_pk_ht,HG_ADcorr_fit, '--r', label = 'Aquadag correction applied')
ax.plot(HG_pk_ht,HG_uncorr_fit, '-r')
plt.xlabel('Incandescent pk height (a.u.)')
plt.ylabel('rBC mass (fg)')
#plt.text(250,10, 'Aquadag corrected fit:\nrBC mass = {number:.{digits}g}'.format(number=HG_fit[0], digits=5) +  ' + ' + '{number:.{digits}g}'.format(number=HG_fit[1], digits=5) + '*pkht + ' + '{number:.{digits}g}'.format(number=HG_fit[2], digits=5) + '*pkht^2')
plt.text(250,15, 'Aquadag corrected fit:\nrBC mass =' + str(round(HG_fit[0],5)) + ' + ' + '{number:.{digits}g}'.format(number=HG_fit[1], digits=5) + '*pkht')
ax.set_ylim(0,24)
ax.set_xlim(0,1500)

plt.legend()
os.chdir('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/calibrations/')
plt.savefig('WHI ECSP2 2009 Aquadag calibration curves.png', bbox_inches='tight')

plt.show()


text:
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 10:20:46 2020

@author: nikbakht
"""

import tensorflow as tf
from tensorflow.keras.layers import Layer
import numpy as np
class Loss(Layer):
    def __init__(self,Nap,Nuser,cost_type,**kwargs):
        super(Loss, self).__init__(**kwargs)
        self.Nap=Nap
        self.Nuser=Nuser
        self.alpha=1
        self.cost_type=cost_type
    def build(self,input_shape):
        pass
    def call(self,SNR,p):

        # with tf.GradientTape() as tape:
        #     tape.watch(p)
        num=tf.zeros([p.shape[0],1], dtype='float32')
        denom=tf.zeros(num.shape, dtype='float32')
        SINR=tf.zeros([SNR.shape[0],self.Nuser], dtype='float32')
        # ta = tf.TensorArray(tf.float32, size=self.Nuser)

        # for k in range(self.Nuser):
        #     num=tf.multiply(p[:,k],SNR[:,k,k])
        #     Total=tf.multiply(p,SNR[:,k,:])
        #     denom=1+tf.reduce_sum(Total,axis=1)-Total[:,k]
        #     ta = ta.write(k,tf.divide(num,denom))

        # SINR=tf.transpose(ta.stack(),perm=[1,0])

        num = p*tf.linalg.diag_part(SNR)
        Total = tf.tile(tf.expand_dims(p,axis=1),[1,self.Nap,1])*SNR
        denom = tf.reduce_sum(Total,axis=2)-tf.linalg.diag_part(Total)
        SINR = num/denom

        if self.cost_type=='maxmin':
                temp=self.alpha*tf.pow(tf.divide(1.0,.01+SINR),.4)
                Cost= tf.reduce_sum(tf.exp(temp),axis=1,keepdims=True)
                const = tf.reduce_sum(tf.nn.relu(p-1),axis=1,keepdims=True)
                Cost = 1.0/self.Nuser*(Cost+.1*const)
                # Cost=tf.reduce_mean(Cost,axis=0)
        elif self.cost_type=='maxproduct':
                temp=tf.pow(0.01+tf.divide(1.0,0.01+SINR),.4)
                Cost=tf.reduce_mean(tf.math.log(temp)
                  +.1*tf.reduce_mean(tf.nn.relu(p-1),axis=1,keepdims=True)
                ,axis=1)
        # temp=tf.pow(tf.divide(1.0,0.01+SINR),.4)
        # Cost=tf.reduce_mean(tf.math.log(0.1+temp)
        #                     +.1*tf.reduce_mean(tf.nn.relu(p-1),axis=1,keepdims=True)
        #                     ,axis=1)

        Cost=tf.reduce_mean(Cost)

        if  tf.math.is_inf(Cost).numpy() or tf.math.is_nan(Cost).numpy():
            print('Cost is inf or nan')
        min_sir = tf.reduce_mean(tf.math.log(tf.math.reduce_min(SINR,axis=1)))
        #--------------------------------------
        # grad = tape.gradient(Cost,p)
        # grad_check = tf.debugging.check_numerics(grad,'Loss: Gradient error')
        # if tf.reduce_sum(tf.cast(tf.math.is_nan(grad),'int32')).numpy():
        #     print('grad is fucked up')
        return Cost,SINR,min_sir

max_stars_repo_name: FerdinandHannequart/Nikbakht

max_issues_repo_name: FerdinandHannequart/Nikbakht

max_forks_repo_name: FerdinandHannequart/Nikbakht


text:
# Copyright 2022 Pulser Development Team
#
# 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 in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

import numpy as np

def square_rect(rows: int, columns: int) -> np.ndarray:
    """A square lattice pattern in a rectangular shape.

    Args:
        rows(int): Number of rows.
        columns(int): Number of columns.

    Returns:
        np.ndarray: The coordinates of the points in the pattern.
    """
    points = np.mgrid[:columns, :rows].transpose().reshape(-1, 2)
    # Centering
    points = points - np.ceil([columns / 2, rows / 2]) + 1
    return points

def triangular_rect(rows: int, columns: int) -> np.ndarray:
    """A triangular lattice pattern in a rectangular shape.

    Args:
        rows(int): Number of rows.
        columns(int): Number of columns.

    Returns:
        np.ndarray: The coordinates of the points in the pattern.
    """
    points = square_rect(rows, columns)
    points[:, 0] += 0.5 * np.mod(points[:, 1], 2)
    points[:, 1] *= np.sqrt(3) / 2
    return points

def triangular_hex(n_points: int) -> np.ndarray:
    """A triangular lattice pattern in an hexagonal shape.

    Args:
        n_points(int): The number of points in the pattern.

    Returns:
        np.ndarray: The coordinates of the points in the pattern.
    """
    # y coordinates of the top vertex of a triangle
    crest_y = np.sqrt(3) / 2.0

    if n_points < 7:
        hex_coords = np.array(
            [
                (0.0, 0.0),
                (-0.5, crest_y),
                (0.5, crest_y),
                (1.0, 0.0),
                (0.5, -crest_y),
                (-0.5, -crest_y),
            ]
        )
        return hex_coords[:n_points]

    layers = int((-3.0 + np.sqrt(9 + 12 * (n_points - 1))) / 6.0)
    points_left = n_points - 1 - (layers**2 + layers) * 3

    # Coordinates of vertices
    start_x = [-1.0, -0.5, 0.5, 1.0, 0.5, -0.5]
    start_y = [0.0, crest_y, crest_y, 0, -crest_y, -crest_y]

    # Steps to place atoms, starting from a vertex
    delta_x = [0.5, 1.0, 0.5, -0.5, -1.0, -0.5]
    delta_y = [crest_y, 0.0, -crest_y, -crest_y, 0.0, crest_y]

    coords = np.array(
        [
            (
                start_x[side] * layer + atom * delta_x[side],
                start_y[side] * layer + atom * delta_y[side],
            )
            for layer in range(1, layers + 1)
            for side in range(6)
            for atom in range(1, layer + 1)
        ],
        dtype=float,
    )

    if points_left > 0:
        layer = layers + 1
        min_atoms_per_side = points_left // 6
        # Extra atoms after balancing all sides
        points_left %= 6

        # Order for placing left atoms
        # Top-Left, Top-Right, Bottom (C3 symmetry)...
        # ...Top, Bottom-Right, Bottom-Left (C6 symmetry)
        sides_order = [0, 3, 1, 4, 2, 5]

        coords2 = np.array(
            [
                (
                    start_x[side] * layer + atom * delta_x[side],
                    start_y[side] * layer + atom * delta_y[side],
                )
                for side in range(6)
                for atom in range(
                    1,
                    min_atoms_per_side + 2
                    if points_left > sides_order[side]
                    else min_atoms_per_side + 1,
                )
            ],
            dtype=float,
        )

        coords = np.concatenate((coords, coords2))

    coords = np.concatenate((np.zeros((1, 2)), coords))
    return coords

max_stars_repo_name: lvignoli/Pulser

max_issues_repo_name: lvignoli/Pulser

max_forks_repo_name: lvignoli/Pulser